次の方法で共有


map::operator[]

map に、指定したキー値を持つ要素を挿入します。

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

パラメーター

パラメーター

説明

_Key

挿入される要素のキー値。

戻り値

挿入される要素のデータ値への参照。

解説

引数のキー値が見つからない場合は、データ型の既定値と一緒に挿入されます。

operator[] が DataValue が _Keyのキー値を持つ要素 mapped_type の値である m[_Key] = DataValue; を使用してマップ m に要素を挿入するために使用されるおそれがあります。

operator[] を使用して要素を挿入した場合、返される参照では、挿入によって既存の要素が変更される、または新しい要素が作成されるかどうかは指示されません。 メンバー関数 find および insert を使用して、挿入前に指定のキーを持つ要素が既に存在するかどうかを確認できます。

使用例

// 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

参照

関連項目

map クラス

標準テンプレート ライブラリ