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));
Share:
111,410
myWallJSON
Author by

myWallJSON

Updated on July 05, 2022

Comments

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

  • nullpotent
    nullpotent over 12 years
    just declare the vector like so std::vector<unsigned char>
  • Etienne de Martel
    Etienne de Martel over 12 years
    @myWallJSON You mean copying data from a string to vector<unsigned char>? If there's an implicit conversion between char and unsigned char (which I think there is, but I'm not sure), then yes, it will work.
  • sehe
    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
    void.pointer over 11 years
    Will this also copy the null-terminator into the vector?
  • R. Martinho Fernandes
    R. Martinho Fernandes over 11 years
    @Robert: As is, not. It can be easily modified to do so if necessary, though.
  • Eric
    Eric about 3 years
    If 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.