Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ unordered_map::begin function is used to return the iterator pointing to the first element of the unordered_map container or one of its bucket.

C++ begin end

Note: There is no guarantee of a specific element to be considered as the first element of the unordered_map (or the bucket). But the range that goes from begin to end contains all elements of the unordered_map container (or the bucket).

Syntax

//container iterator
iterator begin() noexcept;
const_iterator begin() const noexcept;

//bucket iterator
local_iterator begin ( size_type n );
const_local_iterator begin ( size_type n ) const;

Parameters

n Specify the bucket number. It should be lower than the bucket_count.

Return Value

An iterator to the beginning of the unordered_map container or one of its bucket. 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 below example, the unordered_map::begin function is used to return the iterator pointing to the first element of the unordered_map container or one of its bucket. The unordered_map::begin function is often used with unordered_map::end function to specify a range including all elements of the unordered_map container or one of its bucket.

#include <iostream>
#include <unordered_map>
using namespace std;
 
int main (){
  unordered_map<string, string> uMap;
  uMap = {{"CAN", "Ottawa"}, {"USA", "Washington"}, {"IND", "Delhi"}};

  cout<<"The uMap contains: ";
  for(auto it = uMap.cbegin(); it != uMap.cend(); ++it)
    cout<<it->first<<":"<<it->second<<" ";

  cout<<"\n\nThe uMap's bucket contains: ";
  for(unsigned int i = 0; i < uMap.bucket_count(); i++) {
    cout<<"\nBucket #"<<i<<": ";   
    for(auto it = uMap.cbegin(i); it != uMap.cend(i); ++it) {
      cout<<it->first<<":"<<it->second<<" ";
    } 
  } 
  return 0;
}

The output of the above code will be:

The uMap contains: USA:Washington IND:Delhi CAN:Ottawa 

The uMap's bucket contains: 
Bucket #0: 
Bucket #1: 
Bucket #2: IND:Delhi CAN:Ottawa 
Bucket #3: USA:Washington 
Bucket #4: 

❮ C++ - Unordered Map