![]() |
VOOZH | about |
The std::map::begin() and std::map::end() are built-in functions used to retrieve iterators to the beginning and the end of a std::map container. Both functions are member functions of the std::map class defined inside the <map> header file.
Example:
1: one 3: three
You may have noticed that we have decremented the map::end() iterator before dereferencing. The reason for this is mentioned below.
The map::begin() method is used to retrieve a map::iterator pointing to the first element of std::map container. The first element in the map is determined by the specified key ordering.
m.begin()
Parameters
Return Value
The map::end() method is used to retrieve a map::iterator pointing to the theoretical element just after the last element of the map. This element does not exist, and the iterator should be decremented once to access the actual last element.
m.end()
Parameters
Return Value
map::begin() and map::end() are important methods that allows the traversal and access of the map. Their main purpose of map::iterator is to act as a bridge between the STL algorithms and map container.
We can traverse the map by incrementing and dereferencing the map::begin() iterator till it is not equal to the map::end() iterator.
1: one 2: two 3: three
We cannot modify the key of the map elements once it is inserted but we can modify the value associated with it.
1: M one 2: M two 3: M three
We can use the std::distance() function to calculate the number of elements between map::begin() and map::end().
3
The following table lists some primary differences between the std::map::begin() and std::map::end() methods:
| map::begin() | map::end() |
|---|---|
| Returns an iterator to the first element in the map. | Returns an iterator to the first element in the set container. |
Syntax: m.begin(); | Syntax: m.end(); |
We can dereference std::map::begin() iterator because it points to the valid element. | We should not dereference std::map::end() iterator because it does not point to valid element. |