共用方式為


unordered_map::operator[]

尋找或插入具有指定索引鍵的項目。

Ty& operator[](const Key& keyval);
Ty& operator[](Key&& keyval);

參數

參數

描述

Keyval

要尋找或插入的索引鍵值。

傳回值

所插入項目之資料值的參考。

備註

如果找不到引數索引鍵值,則將它與資料類型的預設值一起插入。

operator[] 可用來將項目插入使用 m[_Key] = DataValue 的對應 m 中,其中 DataValue 是具有索引鍵值 _Key 之項目的mapped_type 值。

當使用 operator[] 插入項目時,傳回的參考不會指出插入是變更預先存在的項目,還是建立新的項目。 成員函式 findinsert 可用來判斷有指定之索引鍵的項目是否在插入之前已經存在。

範例

// std__unordered_map__unordered_map_operator_sub.cpp 
// compile with: /EHsc 
#include <unordered_map> 
#include <iostream> 
#include <string>
 
typedef std::unordered_map<char, int> Mymap; 
int main() 
    { 
    Mymap c1; 
 
    c1.insert(Mymap::value_type('a', 1)); 
    c1.insert(Mymap::value_type('b', 2)); 
    c1.insert(Mymap::value_type('c', 3)); 
 
// display contents " [c 3] [b 2] [a 1]" 
    for (Mymap::const_iterator it = c1.begin(); 
        it != c1.end(); ++it) 
        std::cout << " [" << it->first << ", " << it->second << "]"; 
    std::cout << std::endl; 
 
// try to find and fail 
    std::cout << "c1['A'] == " << c1['A'] << std::endl; 
 
// try to find and succeed 
    std::cout << "c1['a'] == " << c1['a'] << std::endl; 
 
// redisplay contents 
    for (Mymap::const_iterator it = c1.begin(); 
        it != c1.end(); ++it) 
        std::cout << " [" << it->first << ", " << it->second << "]"; 
    std::cout << std::endl; 

// insert by moving key
    std::tr1::unordered_map<string, int> c2;
    std::string str("abc");
    std::cout << "c2[std::move(str)] == " << c2[std::move(str)] << std::endl;
    std::cout << "c2["abc"] == " << c2["abc"] << std::endl;
 
    return (0); 
    } 
 
  

備註

成員函式判斷迭代器 where 做為 unordered_map::insert( unordered_map::value_type(keyval, Ty()) 的傳回值 (如果沒有此類項目存在,它會插入具有指定之索引鍵的項目)。然後傳回 (*where).second 的參考。

需求

標頭:<unordered_map>

命名空間: std

請參閱

參考

<unordered_map>

unordered_map 類別

unordered_map::find

unordered_map::insert

其他資源

<unordered_map> 成員