How to copy std::string into std::vector<char>?
111,410
Solution 1
std::vector
has a constructor that takes two iterators. You can use that:
std::string str = "hello";
std::vector<char> data(str.begin(), str.end());
If you already have a vector and want to add the characters at the end, you need a back inserter:
std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));
Solution 2
You need a back inserter to copy into vectors:
std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));
Author by
myWallJSON
Updated on July 05, 2022Comments
-
myWallJSON almost 2 years
Possible Duplicate:
Converting std::string to std::vector<char>I tried:
std::string str = "hello"; std::vector<char> data; std::copy(str.c_str(), str.c_str()+str.length(), data);
but it does not work=( So I wonder How to copy
std::string
intostd::vector<char>
orstd::vector<uchar>
? -
nullpotent over 12 yearsjust declare the vector like so std::vector<unsigned char>
-
Etienne de Martel over 12 years@myWallJSON You mean copying data from a
string
tovector<unsigned char>
? If there's an implicit conversion betweenchar
andunsigned char
(which I think there is, but I'm not sure), then yes, it will work. -
sehe over 12 years@R.Martinho: I'm pretty certain the reserve is unnecessary because common standard library implementations will dispatch to overloads specializing for random-access iterators so they can employ memmove anyway.
-
void.pointer over 11 yearsWill this also copy the null-terminator into the vector?
-
R. Martinho Fernandes over 11 years@Robert: As is, not. It can be easily modified to do so if necessary, though.
-
Eric about 3 yearsIf one needs to set a new value, I recommend using the vector member function
assign
(with the string's begin and end iterators) rather than the more complicated external copy function. In general, when available it is best to make use of provided member functions of a class since library developers have the opportunity of optimizing the implementation with the class in mind.