This post will discuss how to implode a vector of strings into a comma-separated string in C++.

1. Using std::copy function

An elegant solution is to use std::copy to copy the vector’s contents to the string stream using the output iterator. The following solution demonstrates this using std::ostream_iterator, which takes a delimiter on construction and writes it to the stream after inserting each element. This solution works but leaves a trailing delimiter.

Download  Run Code

2. Using std::accumulate

Another option is to use the std::accumulate provided by the standard library. It is defined in the header file <numeric>. To leave no trailing delimiter, perform the concat operation on two strings starting from the second element, as shown below:

Download  Run Code

 
The behavior of this example is equivalent to:

Download  Run Code

3. Using Boost

Another good alternative is to use boost’s boost::algorithm::join function, which is defined in the header file <boost/algorithm/string/join.hpp>. This is demonstrated below:

Download Code

That’s all about imploding a vector of strings into a comma-separated string in C++.