當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。