unordered_map operator[] in C++ STL
Last Updated :
14 Dec, 2018
The std::unordered_map::operator[] is a built in function in C++ STL which returns the reference of value if key matches in the container. If no key is found then it inserts that key into container.
Syntax:
mapped_type& operator[](key_type&& k);
Parameter: It takes parameter as key whose mapped value is accessed.
Return type: Returns a reference associated to that key.
Example 1
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_map< int , int > sample;
sample = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
for ( auto & it : sample)
cout << it.first << " : " << it.second << endl;
int m = sample[1];
sample[3] = m;
sample[5] = sample[1];
m = sample[25];
sample[5] = sample[10];
for ( auto & it : sample)
cout << it.first << " : " << it.second << endl;
return 0;
}
|
Output:
5 : 6
3 : 4
1 : 2
10 : 0
1 : 2
5 : 0
3 : 2
25 : 0
Example 2
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_map< char , int > sample;
sample = { { 'a' , 2 }, { 'b' , 4 }, { 'c' , 6 } };
for ( auto & it : sample)
cout << it.first << " : " << it.second << endl;
int m = sample[ 'a' ];
sample[ 'b' ] = m;
sample[ 'c' ] = sample[ 'a' ];
m = sample[ 'd' ];
sample[ 'c' ] = sample[ 'f' ];
for ( auto & it : sample)
cout << it.first << " : " << it.second << endl;
return 0;
}
|
Output:
c : 6
b : 4
a : 2
f : 0
a : 2
b : 2
c : 0
d : 0
Time Complexity O(n) in worst case.
Share your thoughts in the comments
Please Login to comment...