In this shot, we will learn how to use the unordered_map::end()
function, which is available in the <unordered_map>
header file in C++.
The unordered_map::end()
function is used to return an iterator pointing to the element past the last element in the unordered map. There are two variations of this function:
The syntax of the unordered_map::end()
function is as follows:
iterator end();
iterator end(size_type n);
The function accepts the bucket number as an optional parameter.
If the bucket number is not specified, then it will return the iterator pointing to past the last key-value pair in the map. Otherwise, it will return an iterator pointing to past the last key-value pair in the specified bucket.
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 << "Map contains: " << endl;for(auto it = umap.begin(); it != umap.end(); it++){cout << it->first << " -> " << it->second << endl;}cout << endl;for (int i = 0; i < umap.bucket_count(); ++i){cout << "Bucket " << i << " contains:\n";for (auto it = umap.begin(i); it != umap.end(i); ++it)cout << "(" << it->first << "," << it->second << ")\n";cout << endl;}return 0;}
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 lines 15 and 16, we printed the key-value pair from the map using the unordered_map::end()
function without passing the optional parameter.
In line 20, we ran a loop to obtain the bucket count and traverse to all the buckets.
In line 22, we displayed the bucket number.
In line 23, we ran a loop to iterate over all the elements in the bucket. We used the unordered_map::end()
function to ensure that the iteration stops when the iterator reaches to past the end position.
In line 24, we displayed the key value pairs present in each bucket.