Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> ?

like image 802
myWallJSON Avatar asked Nov 25 '11 01:11

myWallJSON


People also ask

How do you copy a string in vector?

std::string str = "hello"; std::vector<char> data; std::copy(str. c_str(), str. c_str()+str. length(), data);

Does std::string make a copy?

It's called "deep copy". If only the pointer itself was copied and not the memory contents, it would be called "shallow copy". To reiterate: std::string performs deep copy in this case.


1 Answers

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)); 
like image 92
R. Martinho Fernandes Avatar answered Sep 25 '22 10:09

R. Martinho Fernandes