Iterator abstracts the concept of pointer to the sequence in range [begin, end)
, and thus provides the following basic operations:
- dereference to obtain the current element;
- movement to point the next element;
- comparison to determine at least the end of sequence.
Iterator to the element of the sequence in range [begin, end)
is valid from the moment of initialization and until:
- the moment it goes out of the scope;
- the moment of destruction or modifying (such as resizing) the underlying storage (usually, a container where the sequence is actually stored).
Please note, that the sequence range of [begin, end)
is half-opened, since the end
is serves as the element one-past-the-last element of the sequence. An attempt of reading or writing by using the end
may lead to the undefined behavior of the program, and therefore illegal. Iterator that points to the end
is primarily used to determine the end of sequence by using the comparison operator !=
. Also, the end
is conventionally used by functions as the return value to indicate the search failure (i.e. “the requested element not found” condition), for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <algorithm> #include <string> #include <vector> /// Represents a person. struct Person final { int id; std::string name; int age; }; /// @returns `true` if the person with the specified name is presents in `persons`. bool is_person_present(const std::vector<Person>& persons, const std::string_view name) { // [begin, end) covers all the values in persons vector. const auto beg = cbegin(persons); // obtain the `begin` const auto end = cend(persons); // obtain the `end` const auto i = find_if(beg, end, [name](const auto& person) { return person.name == name; }); // returns `end` if no person the specified name in `persons` return i != end; } |