A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/unordered_map-cbegin-in-c-stl/ below:

unordered_map cbegin in C++ STL

unordered_map cbegin in C++ STL

Last Updated : 02 Jan, 2019

cbegin

function in c++ is used to return a constant iterator pointing the first element in an unordered map.

Syntax:
unordered_map.cbegin()
Parameter

: It takes an optional parameter

N

. If set, the iterator returned will point to the first element of the bucket otherwise it point to the first element of the container.

Return values

: A constant iterator pointing to the first element of the unordered_map. Below program illustrate the working of

cbegin

function:

CPP
// CPP program to demonstrate implementation of
// cbegin function in unordered_map
#include <bits/stdc++.h>
using namespace std;

int main()
{
    unordered_map<string, int> mp;

    // Adding some elements in the unordered_map
    mp["g"] = 1;
    mp["e"] = 2;
    mp["k"] = 4;
    mp["s"] = 5;

    cout << "Contents of the unordered_map :\n";
    for (auto it = mp.cbegin(); it != mp.cend(); it++)
        cout << it->first << "==>>"
             << it->second << "\n";
}
Output:
Contents of the unordered_map :
s==>>5
k==>>4
g==>>1
e==>>2

The cbegin() function returns a constant iterator. If we try to change value, we get compiler error.

CPP
// CPP program to demonstrate implementation of
// cbegin function in unordered_map
#include <bits/stdc++.h>
using namespace std;

int main()
{
    unordered_map<string, int> mp;

    // Adding some elements in the unordered_map
    mp["g"] = 1;
    mp["e"] = 2;
    mp["k"] = 4;
    mp["s"] = 5;

    cout << "Contents of the unordered_map :\n";
    for (auto it = mp.cbegin(); it != mp.cend(); it++)
        it->second = 10; // This would cause compiler error
}

Output :


prog.cpp: In function 'int main()':
prog.cpp:18:20: error: assignment of member 'std::pair, int>::second' in read-only object
         it->second = 10; // This would cause compiler error
                    ^
Time Complexity:

O(1) on average.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4