Everyone faces this problem at some point:
for(const auto& item : items) { cout << item << separator; }
... and you get an extra delimiter that you don't want at the end. Sometimes it does not print, but, say, performs some other action, but in order for sequential actions of the same type to require some kind of separator action, but the latter does not.
Now, if you are working with the old school for loops and arrays, you would do
for(int i = 0; i < num_items; i++) cout << items[i]; if (i < num_items - 1) { cout << separator; } }
(or you can exclude the last element from the loop.) If you have something that allows non-destructive iterators, even if you don't know its size, you can do:
for(auto it = items.cbegin(); it != items.cend(); it++) { cout << *it; if (std::next(it) != items.cend()) { cout << separator; } }
I do not like the aesthetics of the last two, and usually for loops. Can I get the same effect as with the last two, but using stronger C ++ 11ish constructs?
To expand the question further (outside of, say,
this ), I will say that I would also like the first or last element to not have a special case explicitly. This is an “implementation detail” that I don’t want to worry about. So, in imaginary-future-C ++ something like this is possible:
for(const auto& item : items) { cout << item; } and_between { cout << separator; }
c ++ idioms c ++ 11 separator
einpoklum Feb 12 '16 at 21:51 2016-02-12 21:51
source share