unordered_map::operator[]
查找或插入具有指定密钥的一个元素。
Ty& operator[](const Key& keyval);
Ty& operator[](Key&& keyval);
参数
Parameter |
说明 |
Keyval |
键值查找的或插入。 |
返回值
对于插入的元素数据值的引用。
备注
如果找不到参数的键值,则它与数据类型以及的默认插入。
operator[] 能用于将元素插入到映射 m 使用 m[] _Key = DataValue;其中 DataValue 是元素的 mapped_type 的值与 _Key 的键值的。
在使用 operator[] 插入元素时,返回的引用不指示插入是否更改预先存在的组件或创建新的。 成员函数 查找 和 插入 可用于确定与指定的键的元素是否在插入之前已存在。
示例
// std_tr1__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