共用方式為


hash_map::operator[]

注意事項注意事項

這個 API 已經過時。這個選項是 unordered_map Class

將項目插入具有指定之索引鍵值的 hash_map

Type& operator[](
   const Key& _Key
);
Type& operator[](
   Key&& _Key
);

參數

參數

描述

_Key

要插入項目的資料索引鍵值。

傳回值

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

備註

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

**operator[]**可用來將項目插入 hash_map m 使用

m[_Key] = DataValue;

其中 DataValue 是項目的 mapped_type 的值與 _Key的外部索引鍵值的。

當使用 operator[] 插入項目時,傳回的參考不會指出外掛程式是否變更一個已經存在的項目或建立新的。 成員函式 尋找 和外掛程式可以用來判斷具有指定索引鍵的項目是否在插入之前已經存在。

範例

// hash_map_op_ref.cpp
// compile with: /EHsc
#include <hash_map>
#include <iostream>
#include <string>

int main( )
{
   using namespace std;
   using namespace stdext;
   typedef pair <const int, int> cInt2Int;
   hash_map <int, int> hm1;
   hash_map <int, int> :: iterator pIter;
   
   // Insert a data value of 10 with a key of 1
   // into a hash_map using the operator[] member function
   hm1[ 1 ] = 10;

   // Compare other ways to insert objects into a hash_map
   hm1.insert ( hash_map <int, int> :: value_type ( 2, 20 ) );
   hm1.insert ( cInt2Int ( 3, 30 ) );

   cout  << "The keys of the mapped elements are:";
   for ( pIter = hm1.begin( ) ; pIter != hm1.end( ) ; pIter++ )
      cout << " " << pIter -> first;
   cout << "." << endl;

   cout  << "The values of the mapped elements are:";
   for ( pIter = hm1.begin( ) ; pIter != hm1.end( ) ; pIter++ )
      cout << " " << pIter -> second;
   cout << "." << endl;

   // If the key already exists, operator[]
   // changes the value of the datum in the element
   hm1[ 2 ] = 40;

   // operator[] will also insert the value of the data
   // type's default constructor if the value is unspecified
   hm1[5];

   cout  << "The keys of the mapped elements are now:";
   for ( pIter = hm1.begin( ) ; pIter != hm1.end( ) ; pIter++ )
      cout << " " << pIter -> first;
   cout << "." << endl;

   cout  << "The values of the mapped elements are now:";
   for ( pIter = hm1.begin( ) ; pIter != hm1.end( ) ; pIter++ )
      cout << " " << pIter -> second;
   cout << "." << endl;

   // opperator[] will also insert by moving a key
   hash_map <string, int> hm2;
   string str("a");
   hm2[move(str)] = 1;
   cout << "The moved key is " << hm2.begin()->first
      << ", with value " << hm2.begin()->second << endl;
}

Output

The keys of the mapped elements are: 1 2 3.
The values of the mapped elements are: 10 20 30.
The keys of the mapped elements are now: 1 2 3 5.
The values of the mapped elements are now: 10 40 30 0.
The moved key is a, with value 1.

需求

標題: <hash_map>

命名空間: stdext

請參閱

參考

hash_map Class

標準樣板程式庫