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 co
There is a little problem with the ++
operator you are using.
You can try:
if (++iter != keywords.end())
out << ", ";
iter--;
This way, ++
will be evaluated before compare the iterator with keywords.end()
.
It's very easy to fix that (taken from my answer here):
bool print_delim = false;
for (auto iter = keywords.begin(); iter != keywords.end( ); iter++ ) {
if(print_delim) {
out << ", ";
}
out << *iter;
print_delim = true;
}
out << endl;
I am using this idiom (pattern?) in many programming languages, and all kind of tasks where you need to construct delimited output from list like inputs. Let me give the abstract in pseudo code:
empty output
firstIteration = true
foreach item in list
if firstIteration
add delimiter to output
add item to output
firstIteration = false
In some cases one could even omit the firstIteration
indicator variable completely:
empty output
foreach item in list
if not is_empty(output)
add delimiter to output
add item to output
I would go with something like this, an easy solution and should work for all iterators.
int maxele = maxele = v.size() - 1;
for ( cur = v.begin() , i = 0; i < maxele ; ++i)
{
std::cout << *cur++ << " , ";
}
if ( maxele >= 0 )
{
std::cout << *cur << std::endl;
}
Can use functors:
#include <functional>
string getSeparatedValues(function<bool()> condition, function<string()> output, string separator)
{
string out;
out += output();
while (condition())
out += separator + output();
return out;
}
Example:
if (!keywords.empty())
{
auto iter = keywords.begin();
cout << getSeparatedValues([&]() { return ++iter != keywords.end(); }, [&]() { return *iter; }, ", ") << endl;
}