当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ unordered_map operator[]用法及代码示例


std::unordered_map::operator []是C++ STL中的内置函数,如果键在容器中匹配,则返回值的引用。如果未找到 key ,则将其插入容器。句法:

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

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

例子1



// C++ code to illustrate the method 
// unordered_map operator[] 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    unordered_map<int, int> 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 <bits/stdc++.h> 
  
using namespace std; 
  
int main() 
{ 
    unordered_map<char, int> 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)。




相关用法


注:本文由纯净天空筛选整理自ankit15697大神的英文原创作品 unordered_map operator[] in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。