Convert a string to a vector of chars in C++
This post will discuss how to convert a string to a vector of chars in C++.
1. Using Range Constructor
The idea is to use the range constructor offered by the vector class, which takes input iterators to the initial and final positions in a range. For converting a string to a vector of chars, we need to pass the input iterator to the beginning and the end of the string, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <vector> int main() { std::string s = "Hello World!"; std::vector<char> v(s.begin(), s.end()); for (const char &c: v) { std::cout << c; } return 0; } |
Output:
Hello World!
2. Using std::copy function
We can also use the standard algorithm std::copy to copy the characters in the string at the end of a vector using a back inserter.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <vector> int main() { std::string s = "Hello World!"; std::vector<char> v; std::copy(s.begin(), s.end(), std::back_inserter(v)); for (const char &c: v) { std::cout << c; } return 0; } |
Output:
Hello World!
The std::back_inserter calls the std::push_back function internally, which takes care of the memory requirements for accommodating all characters in the string.
If the vector already has sufficient memory to accommodate all characters in the string, we can even pass the input iterator to the beginning of the vector to the std::copy algorithm, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <vector> int main() { std::string s = "Hello World!"; std::vector<char> v(s.length()); std::copy(s.begin(), s.end(), v.begin()); for (const char &c: v) { std::cout << c; } return 0; } |
Output:
Hello World!
That’s all about converting a string to a vector of chars in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)