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.
Try this:
Something like this?
I suggest you simply switch the first character with the help of a lambda.
Using boost:
and you obtain a string containing the vector, comma delimited.
EDIT: to remove the last comma, just issue:
I would go with something like this, an easy solution and should work for all iterators.
Another possible solution, which avoids an
if
Depends what you're doing in your loop.