This post will explore how to convert a vector of chars to std::string in C++.

1. Using Range Constructor

The idea is to use a string constructor that can accept input iterators to an initial and final position of the vector, as shown below:

Download  Run Code

Output:

abc

2. Using std::ostringstream function

Another good alternative is to use the std::ostringstream included in <sstream> header file. The idea is to insert all characters into the stream and then write the contents of its buffer to the std::string using its str() function.

Download  Run Code

Output:

abc

3. Using std::transform function

We can also use the standard algorithm std::transform, which applies an operation to elements of the specified range and stores the result in another range, which begins at the specified output iterator. The operation may be a unary operation function, a lambda expression, or an object of a class implementing the () operator. We need to include the <algorithm> header file for this.

Download  Run Code

Output:

abc

4. Using For loop

The idea is to call the push_back() function for each input character. push_back appends the specified character at the end of the string.

Download  Run Code

Output:

abc

 
We can also use the +=operator replacing push_back, which is overloaded for chars.

Download  Run Code

Output:

abc

 
Another good alternative is to call the append() function that appends the specified number of characters at the end of the string.

Download  Run Code

Output:

abc

 
Finally, we also have the insert(pos, n, c) function that inserts n copies of character c beginning at character pos.

Download  Run Code

Output:

abc

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