Is it possible to initialize vector<char> from a string in a single line of code?
I do this:

 vector<char> vec; string str = "To travel you need a wish and your passport"; for (auto it : str) { vec.push_back(it); } 

But I would like to know a more elegant way.

    1 answer 1

     string str = "To travel you need a wish and your passport"; vector<char> vec(str.begin(),str.end()); 

    Good for you?

    Can also

     vector<char> vec(begin(str),end(str)); 

    or better yet

     vector<char> vec(cbegin(str),cend(str)); 

    These options ( begin/end and cbegin/cend , but not str.begin() and str.end() ) will work for the proposed @Abyx

     constexpr char str[] = "..."; 

    but in this case one should not forget that the terminating null character, which also appears in the vector, also enters str .

    • constexpr char str[] = "..." ; - Abyx
    • @Abyx Here you can resort to vector<char> v(begin(str),end(str)); - just take into account that the zero terminating symbol will be added to the vector ... - Harry
    • one
      so end(str)-1 - Abyx
    • @Abyx You see, I am not sure that it is necessary to indicate this in the answer. I will explain myself :) If you work with string , then it is clear what you mean by string . If with a C-style string, then this terminating null character can be significant, and I wouldn't throw it away just like that. This is the case of the author of a particular code. In addition, an empty array may be at hand ... - Harry
    • @Harry, thank you! - Olejan