[英]Copying boost::array<char> to std::string
I am trying to cvopy boost::array<char>
to std::string
. 我正在尝试将
boost::array<char>
为std::string
。
boost::array<char, 1024> _buffer;
std::string data;
std::copy(_buffer.begin(), _buffer.begin()+bytes_transferred, data.begin());
which is not working. 这是行不通的。 So I changed it a little bit.
所以我做了一点修改。
char _buffer[1024];
std::string data;
std::copy(_buffer, _buffer+bytes_transferred, data.begin());
second one is not working either. 第二个也不工作。
The issue here is that copy
assumes that space already exists for the data you're writing; 这里的问题是,
copy
假定您正在写入的数据已经存在空间; it doesn't create any new room for you. 它不会为您创建任何新房间。 Consequently, both of the above pieces of code cause undefined behavior, since you're going to be copying characters to a location where space hasn't previously been reserved.
因此,上述两段代码都会导致未定义的行为,因为您要将字符复制到以前未保留空间的位置。
The best way to do this would be to use the string
constructor: 最好的方法是使用
string
构造函数:
boost::array<char, 1024> _buffer;
std::string data(_buffer.begin(), _buffer.end());
or 要么
char _buffer[1024];
std::string data(_buffer, _buffer + 1024);
This will initialize the string as a copy of the data stored in the array. 这会将字符串初始化为存储在数组中的数据的副本。
Hope this helps! 希望这可以帮助!
You can use back_insert_iterator . 您可以使用back_insert_iterator 。 Assigning to it will call
push_back
function of the underlying container so you don't need to worry with allocating space manually. 对其进行分配将调用基础容器的
push_back
函数,因此您无需担心手动分配空间。
std::copy(_buffer.begin(), _buffer.begin()+bytes_transferred, std::back_inserter(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.