📜  C++ STL中的unordered_map运算符[]

📅  最后修改于: 2021-05-30 02:47:10             🧑  作者: Mango

std :: unordered_map :::运算符[]是C++ STL中的内置函数,如果容器中的键匹配,该函数将返回值的引用。如果未找到任何密钥,则它将该密钥插入容器。
句法:

mapped_type& operator[](key_type&& k);

参数:以参数为键,可访问映射值。
返回类型:返回与该键关联的引用。

例子1

// C++ code to illustrate the method
// unordered_map operator[]
#include 
using namespace std;
  
int main()
{
    unordered_map sample;
  
    // Map initialization
    sample = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
  
    // print element before doing
    // any operations
    for (auto& it : sample)
        cout << it.first << " : " << it.second << endl;
  
    // existing element is read
    int m = sample[1];
  
    // existing element is written
    sample[3] = m;
  
    // existing elements are accessed
    sample[5] = sample[1];
  
    // non existing element
    // new element 25 will be inserted
    m = sample[25];
  
    // new element 10 will be inserted
    sample[5] = sample[10];
  
    // print element after doing
    // operations
    for (auto& it : sample)
        cout << it.first << " : " << it.second << endl;
    return 0;
}
输出:
5 : 6
3 : 4
1 : 2
10 : 0
1 : 2
5 : 0
3 : 2
25 : 0

例子2

// C++ code to illustrate the method
// unordered_map operator[]
#include 
  
using namespace std;
  
int main()
{
    unordered_map sample;
  
    // Map initialization
    sample = { { 'a', 2 }, { 'b', 4 }, { 'c', 6 } };
  
    // print element before doing
    // any operations
    for (auto& it : sample)
        cout << it.first << " : " << it.second << endl;
  
    // existing element is read
    int m = sample['a'];
  
    // existing element is written
    sample['b'] = m;
  
    // existing elements are accessed
    sample['c'] = sample['a'];
  
    // non existing element
    // new element 'd' will be inserted
    m = sample['d'];
  
    // new element 'f' will be inserted
    sample['c'] = sample['f'];
  
    // print element after doing
    // operations
    for (auto& it : sample)
        cout << it.first << " : " << it.second << endl;
    return 0;
}
输出:
c : 6
b : 4
a : 2
f : 0
a : 2
b : 2
c : 0
d : 0

在最坏的情况下,时间复杂度O(n)。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”