kmiklas
kmiklas

Reputation: 13443

`std::forward_list` walk until iterator is null?

Is it possible to walk a std::forward_list, incrementing an iterator, until said interator is null? The old-fashioned way...

In the following example, I create a print() function.

#include <iostream>
#include <forward_list>

void print(std::forward_list<int>::iterator fl_it, std::forward_list<int>::iterator e) {

    while (fl_it != e) {
        std::cout << *fl_it  << ' ';
        ++fl_it;
    }

    std::cout << std::endl;  //-> 1 2 3
}

int main() {
    std::forward_list<int> fl = {1, 2, 3};
    print(fl.begin(), fl.end());
    std::cout << std::endl;
    return 0;
}

Notice how passing an iterator pointing to the end of the list is necessary, so that we know when to stop walking.

What I want to do is simply pass an iterator to the head of the list, and step along until there are no more elements, like so:

void print(std::forward_list<int>::iterator fl_it) {
    while (fl_it != nullptr) {
        std::cout << *fl_it << ' ';
        ++fl_it;
    }
    std::cout << std::endl;
}

My compiler doesn't like this fl_it != nullptr business.

My first inclination was to look for a method to check if the iterator is null, and references the end of the list. Sadly, such a method does not exist.

Any ideas?

Upvotes: 0

Views: 470

Answers (3)

tmlen
tmlen

Reputation: 9090

The iterator is not null when at the end of the list, instead it is equal to the list's end iterator fl.end(). So both iterators need to be passed to the function.

The internal implementation of the iterator depends on the STL library used, for std::forward_list its interface is such that it fulfills the ForwardIterator concept: http://en.cppreference.com/w/cpp/concept/ForwardIterator .

Upvotes: 0

Tapan Chugh
Tapan Chugh

Reputation: 354

You should realise that the iterator object is not exactly a pointer. It is an object and it represents the position of an item in a datastructure. Also incrementing the end iterator does not result in a null iterator. It is undefined behavior. Look at Can an STL map iterator go out of bounds through incrementing?

Upvotes: 0

Nicol Bolas
Nicol Bolas

Reputation: 473966

You don't.

std::forward_list is a standard library container. Like all containers, it goes from begin to end. There are no "null" iterators. Operations therefore are on a range of iterators.

Note that the Range TS proposal intends to allow "sentinel" types instead of requiring end iterators. A single sentinel could compare equal to the end iterator of any range. So forward_list could indeed be updated to have such a value.

But it still wouldn't be a "null" iterator.

Upvotes: 2

Related Questions