What is the unordered_map::begin() function in C++?
In this shot, we will learn how to use the unordered_map::begin() function, which is available in the <unordered_map> header file in C++.
The unordered_map::begin() function is used to return an iterator pointing to the first element in the unordered map.
There are two variations of this function:
- Bucket number: It specifies the bucket number in the map and returns the iterator pointing to the first key-value pair in the specified bucket. The bucket number should be less than the total number of buckets in the map.
- Without passing any parameter: In this case, the function will return an iterator pointing to the first key-value pair in the map.
Syntax
The syntax of the unordered_map::begin() function is as follows:
iterator begin();
iterator begin (size_type n);
Parameter
The function accepts the bucket number as an optional parameter.
Return
If the bucket number is not specified, then it will return the iterator pointing to the first key-value pair in the map. Otherwise, it will return an iterator pointing to the first key-value pair in the specified bucket.
Code
Let’s have a look at the code now.
#include <iostream>#include <unordered_map>using namespace std;int main(){unordered_map<int,string> umap ={{12, "unordered"},{16, "map"},{89, "in"},{66," C++"}};cout <<"The first key-value pair is: ";cout << umap.begin()->first << "-> " << umap.begin()->second;cout << endl;for (int i = 0; i < umap.bucket_count(); ++i){cout << "Bucket " << i << " contains:";for (auto it = umap.begin(i); it != umap.end(i); ++it)cout << "(" << it->first << "," << it->second << ")\n ";cout << endl;}return 0;}
Explanation
- In lines 1 and 2, we imported the required header files.
- In line 5, we made a
main()function. - From lines 7 to 12, we initialized an unordered map with integer type keys and string type values.
- In line 15, we printed the first key-value pair from the map using the
unordered_map::begin()function without passing the optional parameter. - In line 18, we ran a loop to obtain the bucket count and traverse to all the buckets.
- In line 20, we displayed the bucket number.
- In line 21, we ran a loop to iterate over all the elements in the bucket using the
unordered_map::begin()function.unordered_map::begin()is used to get the iterator pointing to the first element. - In line 22, we displayed the key value pairs present inside each bucket.