[英]Initialization of std::string from std::vector<unsigned char> causes error
In C++ we can create a vector from another vector via在 C++ 中,我们可以通过以下方式从另一个向量创建一个向量
std::vector<unsigned char> tmp_1 { &some_vector[i] , &some_vector[j] };
Question : Is there any way to do the same for std::string
?问题:有没有办法对
std::string
做同样的事情?
Something like:类似的东西:
std::string tmp2 { &some_vector[i] , &some_vector[j] };
Attempts to use constructor from documentation always return error;尝试使用文档中的构造函数总是返回错误;
Note: *some_vector is the vector of unsigned chars注意: *some_vector 是无符号字符的向量
UPD : Found answer: had typo so tried to access [-1] element. UPD :找到答案:有错字,所以试图访问 [-1] 元素。
This:这个:
std::string tmp2 { &some_vector[i] , &some_vector[j] };
should work for std::vector
but I would prefer more readable and safer solution:应该适用于
std::vector
但我更喜欢更具可读性和更安全的解决方案:
std::string tmp2 { std::next( some_container, i ) , std::next( some_container.begin(), j ) };
which should work on any container with type, that can be convertible to char
.这应该适用于任何类型的容器,可以转换为
char
。 For example if you or somebody else later would decide to replace std::vector<char>
to std::deque<char>
for whatever reason, your program will suddenly and what is more dangerous quietly start to be unpredictable with &container[i]
.例如,如果您或其他人后来出于任何原因决定将
std::vector<char>
替换为std::deque<char>
,那么您的程序将突然变得更加危险,并且用&container[i]
悄悄地开始变得不可预测.
std::string
has several constructors , some of which can be used to construct the string from a std::vector
, eg: std::string
有几个构造函数,其中一些可用于从std::vector
构造字符串,例如:
// using a char* pointer and a size...
std::string tmp2( reinterpret_cast<char*>(&some_vector[i]), j-i );
// using char* pointers as iterators...
std::string tmp2( &some_vector[i], &some_vector[j] );
// using vector iterators...
std::string tmp2( some_vector.begin()+i, some_vector.begin()+j );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.