This post will discuss how to print elements of a vector separated by a comma in C++.

1. C++17 – Using std::experimental::ostream_joiner

Starting with C++17, you can use std::experimental::ostream_joiner to write successive objects into the output stream separated by a delimiter, using the << operator. The std::experimental::ostream_joiner is a single-pass output iterator defined in <experimental/iterator> header.

Download  Run Code

Output:

1, 2, 3, 4, 5

2. Using for-loop

Another solution is to use a simple for-loop with an explicit check to print a delimiter before an element or not.

Download  Run Code

Output:

1, 2, 3, 4, 5

3. Using range-based for-loop

Alternatively, you can use a range-based for-loop and print the delimiter before all elements (except for the beginning of the range).

Download  Run Code

Output:

1, 2, 3, 4, 5

4. Using std::ostream_iterator

You can avoid for-loops, and copy the vector’s contents directly to the output stream using the output iterator std::ostream_iterator.

Download  Run Code

Output:

1, 2, 3, 4, 5,

 
The code can be easily modified to avoid printing an extra comma.

Download  Run Code

Output:

1, 2, 3, 4, 5

5. C++20 – Using foreach loop

Starting C++20, you can use foreach loop with an init-statement to handle special-case for the first iteration, as demonstrated below:

Download Code

Output:

1, 2, 3, 4, 5

That’s all about printing elements of a vector separated by a comma in C++.