Skip to content
Related Articles

Related Articles

Improve Article

unordered_map begin() in C++

  • Difficulty Level : Basic
  • Last Updated : 11 Jun, 2021

The unordered_map::begin() is a built-in function in C++ STL which returns an iterator pointing to the first element in the unordered_map container or in any of its bucket. 
 

  1. Syntax for first element in unordered_map container: 
     
unordered_map.begin()
  1. Parameters: This function does not accepts any parameters. 
    Return Value: The function returns an iterator pointing to the first element in the unordered_map container. 
    Note: In an unordered map, there is no specific element which is considered as the first element. 
    Below program illustrate the above function. 
     

CPP




// CPP program to demonstrate the
// unordered_map::begin() function
// when first element of the container
// is to be returned as iterator
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // Declaration
    unordered_map<std::string, std::string> mymap;
 
    // Initialisation
    mymap = { { "Australia", "Canberra" },
              { "U.S.", "Washington" },
              { "France", "Paris" } };
 
    // Iterator pointing to the first element
    // in the unordered map
    auto it = mymap.begin();
 
    // Prints the elements of the first element in map
    cout << it->first << " " << it->second;
 
    return 0;
}
  1.  
Output: 
France Paris

 

  1. Syntax for first element in unordered_map bucket: 
     
unordered_map.begin( n )
  1. Parameters: The function accepts one mandatory parameter n which specifies the bucket number whose first element’s iterator is to be returned. 
    Return Value: The function returns an iterator pointing to the first element in the n-th bucket. 
    Below program illustrate the above function. 
     

CPP




// CPP program to demonstrate the
// unordered_map::begin() function
// when first element of n-th container
// is to be returned as iterator
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // Declaration
    unordered_map<std::string, std::string> mymap;
 
    // Initilisation
    mymap = { { "Australia", "Canberra" },
            { "U.S.", "Washington" }, { "France", "Paris" } };
 
    // Iterator pointing to the first element
    // in the n-th bucket
    auto it = mymap.begin(0);
 
    // Prints the elements of the n-th bucket
    cout << it->first << " " << it->second;
 
    return 0;
}
  1.  
Output: 
U.S. Washington

 

 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :