How to copy std::string into std::vector<char>?

C++StringVectorCopy

C++ Problem Overview


> 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 into std::vector<char> or std::vector<uchar> ?

C++ Solutions


Solution 1 - C++

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 - C++

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmyWallJSONView Question on Stackoverflow
Solution 1 - C++R. Martinho FernandesView Answer on Stackoverflow
Solution 2 - C++Sergey KalinichenkoView Answer on Stackoverflow