This post will discuss how to convert a vector to a string in C++.

1. Using String Constructor

If the vector is of type char, we can use the range constructor to construct a string object by copying the specified range of characters to it. This is demonstrated below:

Download  Run Code

2. Using String Stream

Another option to convert a std::vector to a std::string separated by a delimiter is using the string stream. The following C++ program demonstrates its usage using the iterator-based for loop:

Download  Run Code

 
Here’s an equivalent version using the index-based for-loop:

Download  Run Code

3. Using std::copy

Another alternative is to use the std::copy standard algorithm with the std::ostream_iterator class. It can be used as follows to get a comma-delimited string from a vector:

Download  Run Code

4. Using std::accumulate

Another option to convert a vector to a string is using the standard function std::accumulate, defined in the header <numeric>. We can overwrite its default operation by providing a binary predicate to perform the concat operation on two strings and return the result.

Download  Run Code

5. Using Boost

If your project is open to boost library, consider using the boost::algorithm::join algorithm. It joins all elements in the specified list into a string, where segments are concatenated by a given separator.

Download Code

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