If this is valid:
unsigned char buffer[] = {
0x01, 0x02, 0x03, 0x04
};
Does this apply to std::string as well, e.g.
std::string buffer = {
0x01, 0x02, 0x03, 0x04
};
If not, how do I insert such values?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Not in C++03, but you can do this in C++011:
Demo : http://www.ideone.com/1cOuX. In the demo, I used printable characters (
'A','B'etc) just for the sake of demonstration.In C++03, since the solution given by @andrewdski is admittedly ugly, you can do this instead:
which is a bit cleaner approach. And if you want to add more values later on, then you can do this:
And if you want to add values from other
std::string, then you can do this:which is same as:
By the way, you can write a small utility called
jointhat can do that, in addition to other interesting thing:You can even mix different types in a single
joinstatement as:This is impossible with
{}approach even in C++011.The utility and a complete demo of it is shown below:
Output:
Online Demo : http://www.ideone.com/3Y7pB
However, this utility requires casting with the specific values which you want to insert to the string as:
No so cool, admittedly. The cast is needed otherwise each value will be treated as
inttype which you don’t want. So I would advocate the cleaner approach shown earlier. But this utility can help you in some other scenario. And its good to experiment with C++ operator and features, sometimes. 😀