Reputation: 12207
I got a piece of code like this:
template<class Iter>
void printRange(Iter begin, Iter last) {
for (Iter i = begin; i != last; i++) {
std::cout << *i << ", ";
}
outstd::cout << *last << ", ";
}
My question is: how can i print out the last element, too, elegantly? Couting the last element individually after the loop does not seem to be a nice and correct solution, ... Is there a better way? Note that i cannot use the <= operator or boost or any stl specific feature either.
Upvotes: 2
Views: 996
Reputation: 157484
You can output the separator conditionally:
template<class Iter>
void printContainer(Iter first, Iter last) {
for (Iter i = first, end = ++last; i != end; i++) {
std::cout << (i == first ? "" : ", ") << *i;
}
}
For a more standard [begin, end)
half-open range:
template<class Iter>
void printContainer(Iter begin, Iter end) {
for (Iter i = begin; i != end; i++) {
std::cout << (i == begin ? "" : ", ") << *i;
}
}
Upvotes: 2
Reputation: 19473
you can do:
template<class Iter>
void printContainer(Iter begin, Iter last) {
Iter afterEnd = end;
afterEnd++;
for (Iter i = begin; i != afterEnd; i++) {
std::cout << *i << ", ";
}
outstd::cout << *last << ", ";
}
but notice that if end
was given by STL libs (like list.end()
) it's already a value after the last element, and ++
will throw an exception.
so I would use the code you have in the way you have it. but when I was calling it I pass it the value after the last value I want to print.
Upvotes: 0
Reputation: 581
For the STL container classes, the iterator value end is after the last item. Once end is reached, it can quit, because all items have been handled.
Upvotes: 4
Reputation: 20938
In The STL, there is a last iterator that does not hold a value, so your loop would work in this case.
Maybe you should consider adding another iterator at the end of your list that does not contain any value, so you would be consistent with the STL.
Upvotes: 0