简体   繁体   中英

Iterate over range with given first and last iterator

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.

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.

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;
    }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM