I know how to do this in other languages, but not C++, which I am forced to use here.
I have a Set of Strings that I'm printing to out in a list, and they need a comma between each one, but not a trailing comma. In java for instance, I would use a stringbuilder and just delete the comma off the end after I've built my string. How do I do it in C++?
auto iter = keywords.begin();
for (iter; iter != keywords.end( ); iter++ )
{
out << *iter << ", ";
}
out << endl;
I initially tried inserting this block to do it (moving the comma printing here)
if (iter++ != keywords.end())
out << ", ";
iter--;
I hate when the small things trip me up.
EDIT: Thanks everyone. This is why I post stuff like this here. So many good answers, and tackled in different ways. After a semester of Java and assembly (different classes), having to do a C++ project in 4 days threw me for a loop. Not only did I get my answer, I got a chance to think about the different ways to approach a problem like this. Awesome.
If the values are
std::string
s you can write this nicely in a declarative style with range-v3For other types which have to be converted to string you can just add a transformation calling
to_string
.Use an infix_iterator:
Usage would be something like:
In an experimental C++17 ready compiler coming soon to you, you can use
std::experimental::ostream_joiner
:Live examples using GCC 6.0 SVN and Clang 3.9 SVN
In python we just write:
so why not:
and then just use it like:
Unlike in the python example above where the
" "
is a string and thekeywords
has to be an iterable of strings, here in this C++ example the separator andkeywords
can be anything streamable, e.g.Could be like so..
My typical method for doing separators (in any language) is to use a mid-tested loop. The C++ code would be:
(note: An extra
if
check is needed prior to the loop if keywords may be empty)Most of the other solutions shown end up doing an entire extra test every loop iteration. You are doing I/O, so the time taken by that isn't a huge problem, but it offends my sensibilities.