Copy boost :: array <char> to std :: string

I am trying cvopy boost::array<char> to std::string .

 boost::array<char, 1024> _buffer; std::string data; std::copy(_buffer.begin(), _buffer.begin()+bytes_transferred, data.begin()); 

which does not work. So I changed it a little.

 char _buffer[1024]; std::string data; std::copy(_buffer, _buffer+bytes_transferred, data.begin()); 

the second one doesn't work either.

+7
source share
2 answers

You can use back_insert_iterator . Assigning it will call the push_back function of the base container, so you don’t have to worry about manually allocating space.

 std::copy(_buffer.begin(), _buffer.begin()+bytes_transferred, std::back_inserter(data)); 
+5
source

The problem is that copy assumes that space already exists for the data you write; he does not create a new room for you. Therefore, both of the above code snippets cause undefined behavior, since you are going to copy the characters to a place where previously no place was reserved.

The best way to do this is to use the string constructor:

 boost::array<char, 1024> _buffer; std::string data(_buffer.begin(), _buffer.end()); 

or

 char _buffer[1024]; std::string data(_buffer, _buffer + 1024); 

This initializes the string as a copy of the data stored in the array.

Hope this helps!

+15
source

All Articles