In this C++ tutorial, you shall learn how to join elements of a vector into a string, by a delimiter, with example programs.

Join elements of a Vector into a string in C++

To join elements of a vector into a string, by a delimiter, we can use boost library.

Include <boost/algorithm/string/join.hpp>, call join() method, and pass the vector and delimiter string as arguments. The method returns a string where the elements of given vector are joined by the given delimiter.

The syntax of the expression to join the elements of a vector v and that returns a string is

</>
Copy
boost::algorithm::join(v, ", ")

C++ Program

In the following program, we take a vector in v and join the elements of the vector into a string with ", " as delimeter.

main.cpp

</>
Copy
#include <iostream>
#include <vector>
#include <boost/algorithm/string/join.hpp>
using namespace std;

int main() {
   //string vector
   vector<string> v { "apple", "banana", "avocado", "fig" };

   //join elements of vector
   string output = boost::algorithm::join(v, ", ");

   //print joined string
   cout << output;
}

Output

apple, banana, avocado, fig

Conclusion

In this C++ Tutorial, we learned how to join elements of a vector into a string, where the elements are joined by a delimiter string.