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:

Download  Run Code

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.

Download  Run Code

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:

Download  Run Code

Output:

Hello World!

That’s all about converting a string to a vector of chars in C++.