C++ map - begin() Function
The C++ map::begin function returns the iterator pointing to the first element of the map. Please note that, Map is an ordered data container which implies all its elements are ordered all the time.
Syntax
iterator begin(); const_iterator begin() const;
iterator begin() noexcept; const_iterator begin() const noexcept;
Parameters
No parameter is required.
Return Value
An iterator to the beginning of the sequence container. If the sequence object is constant qualified, the function returns a const_iterator, else returns an iterator.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the map::begin function returns the iterator pointing to the first element of the map called MyMap.
#include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; map<int, string>::iterator it; MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; MyMap[104] = "Jo"; MyMap[105] = "Ramesh"; it = MyMap.begin(); cout<<it->first<<" "<<it->second<<"\n"; it++; cout<<it->first<<" "<<it->second<<"\n"; it++; cout<<it->first<<" "<<it->second<<"\n"; return 0; }
The output of the above code will be:
101 John 102 Marry 103 Kim
Example:
Lets see another example of map where map::begin function is with map::end function to specify a range including all elements of the map container.
#include <iostream> #include <map> using namespace std; int main (){ map<string, int> MyMap; map<string, int>::iterator it; MyMap["John"] = 2500; MyMap["Jack"] = 2600; MyMap["Ella"] = 2000; MyMap["Nora"] = 3000; MyMap["Adam"] = 3100; cout<<"MyMap contains: \n "; for(it = MyMap.begin(); it != MyMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n "; return 0; }
The output of the above code will be:
MyMap contains: Adam 3100 Ella 2000 Jack 2600 John 2500 Nora 3000
❮ C++ <map> Library