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();
}
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With