unordered_map begin() Function in C++ with Examples

C++ unordered_map begin() Function: Here, we will learn about the begin() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on May 26, 2022

unordered_map:

An unordered_map is a special type of container that stores data in the form of key-value pairs in an unordered manner. The key stored is used to identify the data value mapped to it uniquely.

std::unordered_map::begin() Function

The begin() function in the unordered map is used to return the iterator that points to the first element of the unordered_map container.

Syntax:

unordered_map.begin();

Parameter(s): It does not accept any parameter for its working.

Return Value: It returns an iterator which points towards the first elements present in the unordered_map.

Note: The unordered_map does not follow any strict indexing pattern, hence there is no specific first element but generally, the last element is returned by begin() function.

C++ unordered_map begin() Function Example 1:

// C++ program to illustrate working of 
// begin() function on unordered_map

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

int main()
{
    // Creating unordered_map
    unordered_map<int, string> unorderedMap;
    unorderedMap = { { 1, "Scala" }, { 2, "Python" }, { 3, "JavaScript" }, { 4, "C++" } };

    // Printing unordered_map elements
    cout << "The elements of unordered_map are ";
    for (auto& val : unorderedMap)
        cout << val.first << " : " << val.second << " ";

    auto it = unorderedMap.begin();
    cout << "\nThe value returned by begin() function : " << it->first << " : " << it->second;

    return 0;
}

Output:

The elements of unordered_map are 4 : C++ 3 : JavaScript 2 : Python 1 : Scala 
The value returned by begin() function : 4 : C++

C++ unordered_map begin() Function Example 2:

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

int main()
{
    // Declaration
    unordered_map<std::string, std::string> cities;

    // Initialisation
    cities = { { "NewDelhi", "India" },
        { "NewYork", "America" }, { "Mumbai", "India" } };

    // Iterator pointing to the first element
    auto it = cities.begin(0);

    // Prints the elements of the n-th bucket
    cout << it->first << " " << it->second;

    return 0;
}

Output:

NewYork America



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.