Logo

Programming-Idioms

History of Idiom 53 > diff from v45 to v46

Edit summary for version 46 by Carlos:
[Cpp] case needs break

Version 45

2017-06-07, 15:59:40

Version 46

2017-08-11, 08:14:18

Idiom #53 Join a list of strings

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

Illustration

Idiom #53 Join a list of strings

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

Illustration
Imports
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
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();
}
Code
std::vector<std::string> x;

const char* const delim = ", ";

switch (x.size())
{
	case 0: y = "";   break;
	case 1: y = x[0]; break;
	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
Origin
http://stackoverflow.com/questions/5288396/c-ostream-out-manipulation/5289170#5289170