Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value using curly braces/bracket to std::string

Tags:

c++

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?

like image 204
freonix Avatar asked Dec 04 '22 22:12

freonix


1 Answers

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

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

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:

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

which is a bit cleaner approach. And if you want to add more values later on, then 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 other std::string, then you can do this:

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

which is same as:

buffer += s; //cool 

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

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

You can even mix different types in a single join statement as:

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

This is impossible with {} approach even in C++011.

The utility and a complete demo of it is 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 the specific values which you want to insert to the string as:

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

No so cool, admittedly. The cast is needed otherwise each value will be treated as int type 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. :D

like image 147
Nawaz Avatar answered Jan 08 '23 16:01

Nawaz