Search⌘ K

Join Container Elements into a String

Explore how to join elements from any container into a formatted string using iterators and ostream in C++. Understand how to avoid trailing separators and create flexible join functions that work with various container types and views.

We'll cover the following...

Sometimes, there is no algorithm in the library to accomplish a task at hand. We can use iterators, with the same techniques as the algorithms library, to easily write one.

For example, we often need to join elements from a container, with separators, into a string. One common solution is to use a simple for() loop:

for(auto v : c) cout << v << ', ';

The problem with this otherwise simple solution is that it leaves a trailing separator Trailing separator refers to a separator character or symbol placed at the end of a series or list, except for the last item, to visually indicate the separation between elements. :

vector<string> greek{ "alpha", "beta", "gamma",
"delta", "epsilon" };
for(auto v : greek) cout << v << ", ";
cout << '\n';

Output:

alpha, beta, gamma, delta, epsilon,

This may be fine in a testing environment, but in any production system, that trailing comma is unacceptable.

The ranges::views library has a join() function, but it doesn't provide a separator:

auto greek_view = views::join(greek);
...