Assign value using curly brackets / brackets to std :: string

If this is valid:

unsigned char buffer[] = { 0x01, 0x02, 0x03, 0x04 }; 

This also applies to std :: string, e.g.

 std::string buffer = { 0x01, 0x02, 0x03, 0x04 }; 

If not, how do I insert such values?

+4
source share
2 answers

Not in C ++ 03, but you can do it in C ++ 011:

  std::string buffer = { 0x01, 0x02, 0x03, 0x04 }; //C++011 ONLY 

Demo: http://www.ideone.com/1cOuX . In the demo, I used printed characters ( 'A' , 'B' , etc.) for demonstration only.


In C ++ 03, since the solution given by @andrewdski is admittedly ugly, you can do this instead:

  unsigned char values[] = {0x01, 0x02, 0x03, 0x04 }; std::string buffer(values, values + sizeof(values)); 

which is a cleaner approach. And if you want to add more values ​​later, you can do this:

 unsigned char more_values[] = {0x05, 0x06, 0x07, 0x08 }; buffer.insert(buffer.end(), more_values, more_values+ sizeof(more_values)); 

And if you want to add values ​​from another std::string , you can do this:

 //add values from s to buffer buffer.insert(buffer.end(), s.begin(), s.end()); 

which matches with:

 buffer += s; //cool 

By the way, you can write a small utility called join that can do this, in addition to another interesting thing:

 std::string s = join() + 'A' + 'B' + 'C' + 'D'; 

You can even mix different types in the same join expression as:

 std::string s = join() + 'A' + 'B' + 'C' + 'D' + "haha" + 9879078; 

This is not possible with the approximation {} even in C ++ 011.

The utility and its full demonstration are shown below:

 #include <iostream> #include <string> #include <sstream> struct join { std::stringstream ss; template<typename T> join & operator+(const T &data) { ss << data; return *this; } operator std::string() { return ss.str(); } }; int main() { std::string s1 = join() + 'A' + 'B' + 'C' + 'D'; std::cout << s1 << std::endl; std::string s2 = join() + 'A' + 'B' + 'C' + 'D' + "haha" + 9879078; std::cout << s2 << std::endl; } 

Output:

 ABCD ABCDhaha9879078 

Online Demo: http://www.ideone.com/3Y7pB

However, this utility requires casting with certain values ​​that you want to insert into the string, like:

 std::string buffer=join()+ (char)0x01 +(char)0x02 + (char)0x03 + (char)0x04; 

Not so great, really. A throw is needed, otherwise each value will be considered an int type that you do not want. Therefore, I will advocate for the cleaner approach shown earlier. But this utility may help you in another scenario. And its useful to experiment with C ++ operator and functions, sometimes .: D

+9
source
 std::string buffer = "\x01\x02\x03\x04" 

is kind of ugly, but it works.

+7
source

All Articles