November 1st, 2013

nyaload

join vector of strings c++ with comma separator

Sometimes I need to join list of strings, like this in python: ', '.join(my_list).
I frequently see some complicated code with boolean mutable variables with names like "bool isFirstElement = true; for (...) { if (!isFirstElement) { ... ; isFirstElement = false; } }"
If you prefer for-loops, or can't use something like <boost/algorithm/string/join.hpp> from your framework, don't use boolean variables. You can write just something like "add separator, if iterator-or-index isn't at start".

Example:
std::vector<std::string> v = ...; std::string result; // std::cout/std::stringstream can be used as well, with the same big-O() performance for (size_t i = 0, i_end = v.size(); i < i_end; ++i) { result += (i ? ", " : ""); // main line in this blog-post result += v[i]; }

For streams, or when you don't worry about temporary strings, the loop body is one-liner:
for (size_t i = 0, i_end = v.size(); i < i_end; ++i) std::cout <<(i ? ", " : "") << v[i]; for (size_t i = 0; i < v.size(); ++i) result += (i ? ", " : "") + v[i];


Alternatives: http://stackoverflow.com/questions/1430757/c-array-to-string

Puzzle for C/C++ hackers: what does (b[&"separator"] - b) mean, where `b' is bool variable?
bool b = ...; //true or false std::cout << (b[&"separator"] - b)