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
A combination of c++11 lambda and macro:
#define INFIX_PRINTER(os, sep)([&]()->decltype(os)&{static int f=1;os<<(f?(f=0,""):sep);return os;})()
Usage:
for(const auto& k: keywords)
INFIX_PRINTER(out, ", ") << k;
In an experimental C++17 ready compiler coming soon to you, you can use std::experimental::ostream_joiner:
#include <algorithm>
#include <experimental/iterator>
#include <iostream>
#include <iterator>
int main()
{
int i[] = {1, 2, 3, 4, 5};
std::copy(std::begin(i),
std::end(i),
std::experimental::make_ostream_joiner(std::cout, ", "));
}
Live examples using GCC 6.0 SVN and Clang 3.9 SVN
I suggest you simply switch the first character with the help of a lambda.
std::function<std::string()> f = [&]() {f = [](){ return ","; }; return ""; };
for (auto &k : keywords)
std::cout << f() << k;
I think this should work
while (iter != keywords.end( ))
{
out << *iter;
iter++ ;
if (iter != keywords.end( )) out << ", ";
}
I think this variant of @MarkB's answer strikes optimal balance of readability, simplicity and terseness:
auto iter= keywords.begin();
if (iter!=keywords.end()) {
out << *iter;
while(++iter != keywords.end())
out << "," << *iter;
}
out << endl;
This one overloads the stream operator. Yes global variables are evil.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
int index = 0;
template<typename T, template <typename, typename> class Cont>
std::ostream& operator<<(std::ostream& os, const Cont<T, std::allocator<T>>& vec)
{
if (index < vec.size()) {
if (index + 1 < vec.size())
return os << vec[index++] << "-" << vec;
else
return os << vec[index++] << vec;
} else return os;
}
int main()
{
std::vector<int> nums(10);
int n{0};
std::generate(nums.begin(), nums.end(), [&]{ return n++; });
std::cout << nums << std::endl;
}