unordered_map::operator[]

更新 : 2007 年 11 月

指定したキーを持つ要素を検索または挿入します。

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

パラメータ

  • keyval
    検索または挿入するキー値。

使用例

 

// std_tr1__unordered_map__unordered_map_operator_sub.cpp 
// compile with: /EHsc 
#include <unordered_map> 
#include <iostream> 
 
typedef std::tr1::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; 
 
    return (0); 
    } 
 
 [c, 3] [b, 2] [a, 1]
c1['A'] == 0
c1['a'] == 1
 [c, 3] [b, 2] [A, 0] [a, 1]

解説

このメンバ関数は、unordered_map::insert( unordered_map::value_type(keyval, Ty()) の戻り値として反復子 where を特定します。そのような要素が存在しない場合は、指定されたキーを持つ要素を挿入します。その後、(*where).second への参照を返します。

必要条件

ヘッダー : <unordered_map>

名前空間 : std::tr1

参照

参照

<unordered_map>

unordered_map クラス

unordered_map::find

unordered_map::insert