unordered_map at() Function in C++ with Examples

C++ unordered_map at() Function: Here, we will learn about the at() 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::at() Function

The unordered_map library in C++ contains many utility functions to support the working of the structure. One of them is at the at() method which is used to extract the value present in the map for the key k.

Syntax:

mapped_type& at ( const key_type& k );
const mapped_type& at ( const key_type& k ) const;

// or
unordered_mapName.at(keyName);

Parameter(s): It accepts a single parameter which is the key whose mapped value is to be searched.

Return Value: It returns the value which is mapped to the given key. If no key value is present the function will throw an exception.

C++ unordered_map at() Function Example 1:

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

using namespace std;

int main()
{
    unordered_map<string, int> myMap = { { "val2", 432 }, { "val3", 12 }, { "val1", 3 }, { "val4", 411 } };

    cout << "The elements of unordered_map are ";

    for (auto& val : myMap) {
        cout << val.first << " : " << val.second << " ";
    }

    cout << "\nValue of at key 'second' = " << myMap.at("val3") << endl;

    return 0;
}

Output:

The elements of unordered_map are val4 : 411 val1 : 3 val3 : 12 val2 : 432 
Value of at key 'second' = 12

C++ unordered_map at() Function Example 2:

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

using namespace std;

int main()
{
    unordered_map<string, int> myMap = { { "val2", 432 }, { "val3", 12 }, { "val1", 3 }, { "val4", 411 } };

    cout << "The elements of unordered_map are ";

    for (auto& val : myMap) {
        cout << val.first << " : " << val.second << " ";
    }

    cout << "\nValue of at key 'second' : ";
    try {
        myMap.at("val5");
    }

    catch (const out_of_range& e) {
        cerr << "Exception at " << e.what() << endl;
    }

    return 0;
}

Output:

The elements of unordered_map are val4 : 411 val1 : 3 val3 : 12 val2 : 432 
Value of at key 'second' : Exception at _Map_base::at

When an out of range or a value that is not present in the unordered_map is passed to the function. It throws an error, as the error will terminate the program we have used the try-catch block to show the functioning.





Comments and Discussions!

Load comments ↻






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