map::operator[]
將具有特定索引鍵值的項目插入對應中。
Type& operator[](
const Key& _Key
);
Type& operator0-(
Key&& _Key
);
參數
參數 |
說明 |
_Key |
要插入項目的索引鍵值。 |
傳回值
要插入的項目之資料值的參考。
備註
如果引數索引鍵值找不到,則它與資料型別的預設值一起插入。
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