Logo

Programming-Idioms

History of Idiom 53 > diff from v36 to v37

Edit summary for version 37 by :
New Cpp implementation by user [TinyFawks]

Version 36

2016-02-18, 17:24:23

Version 37

2016-02-20, 07:00:07

Idiom #53 Join a list of strings

Concatenate elements of string list x joined by the separator ", " to create a single string y.

Idiom #53 Join a list of strings

Concatenate elements of string list x joined by the separator ", " to create a single string y.

Imports
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
Code
std::vector<std::string> x;

const char* const delim = ", ";

switch (x.size())
{
	case 0:
		y = "";
	case 1:
		y = x[0];
	default:
		std::ostringstream os;
		std::copy(x.begin(), x.end() - 1,
			std::ostream_iterator<std::string>(os, delim));
		os << *x.rbegin();
		y = os.str();
}
Origin
http://stackoverflow.com/questions/5288396/c-ostream-out-manipulation/5289170#5289170