map::operator[]
在映射中插入具有指定键值的元素。
Type& operator[](
const Key& _Key
);
Type& operator0-(
Key&& _Key
);
参数
参数 |
说明 |
_Key |
将插入元素的键值。 |
返回值
为 Insert 的元素数据值的引用。
备注
如果关键参数未找到值,则它与数据类型的默认值。插入。
operator[] 可用于将元素插入到 m 的映射是使用 DataValue 元素 mapped_type 值用键值的 _Key的 m[_Key] = DataValue;。
当使用 operator[] 插入元素,则返回的引用不指示插入是否更改预先存在的元素或创建新查询。 成员函数 查找插入 和来确定用指定的键的元素是否在插入之前已存在。
示例
// map_op_insert.cpp
// compile with: /EHsc
#include <map>
#include <iostream>
#include <string>
int main( )
{
using namespace std;
typedef pair <const int, int> cInt2Int;
map <int, int> m1;
map <int, int> :: iterator pIter;
// Insert a data value of 10 with a key of 1
// into a map using the operator[] member function
m1[ 1 ] = 10;
// Compare other ways to insert objects into a map
m1.insert ( map <int, int> :: value_type ( 2, 20 ) );
m1.insert ( cInt2Int ( 3, 30 ) );
cout << "The keys of the mapped elements are:";
for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
cout << " " << pIter -> first;
cout << "." << endl;
cout << "The values of the mapped elements are:";
for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
cout << " " << pIter -> second;
cout << "." << endl;
// If the key already exists, operator[]
// changes the value of the datum in the element
m1[ 2 ] = 40;
// operator[] will also insert the value of the data
// type's default constructor if the value is unspecified
m1[5];
cout << "The keys of the mapped elements are now:";
for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
cout << " " << pIter -> first;
cout << "." << endl;
cout << "The values of the mapped elements are now:";
for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
cout << " " << pIter -> second;
cout << "." << endl;
// insert by moving key
map<string, int> c2;
string str("abc");
cout << "c2[move(str)] == " << c2[move(str)] << endl;
cout << "c2["abc"] == " << c2["abc"] << endl;
return (0);
}
要求
标头: <map>
命名空间: std