Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether the iterator hit the end without container?

Tags:

c++

stl

For example, how to implement the following function without any other information?

bool isEnd(set<int> :: iterator itr);

I know I can do it like this, but how to do it without input variable "s"?

bool isEnd(const set<int> &s, set<int> :: iterator itr) {
    return itr == s.end();
}
like image 209
ArkChar Avatar asked Sep 01 '13 04:09

ArkChar


People also ask

How do you get to the end of an iterator?

To get the last element in an iterator loop you can use std::next() (from C++11). The loop is generally terminated by iterator != container. end() , where end() returns an iterator that points to the past-the-end element.

What is end () iterator?

The list::end() is a built-in function in C++ STL which is used to get an iterator to past the last element. By past the last element it is meant that the iterator returned by the end() function return an iterator to an element which follows the last element in the list container.

Where does end iterator point?

In something like an std::vector the ::end() iterator will point to one past the last element. You can't dereference this iterator but you can compare it to another iterator. If you compare another iterator to end() you know you've reached the end of the container.

What happens if you increment the iterator past the end?

Obviously if the iterator is advanced past the last element inside the loop the comparison in the for-loop statement will evaluate to false and the loop will happily continue into undefined behaviour.


2 Answers

You do not.

A range is two iterators, and you should almost always be working on a range when you are moving iterators around.

Containers are also ranges, so you can carry the container around instead, but usually you do not need the full container.

like image 135
Yakk - Adam Nevraumont Avatar answered Sep 19 '22 09:09

Yakk - Adam Nevraumont


With the standard C++ library, there is no way to write that.

std::set can be implemented as e.g. red-black trees, and then iterators are nodes inside, and you need the entire tree to figure out if that node is the last.

like image 29
Basile Starynkevitch Avatar answered Sep 21 '22 09:09

Basile Starynkevitch