Translations of this page?:

insert

Syntax:

#include <map>
iterator insert( iterator pos, const T& pair );
void insert( input_iterator start, input_iterator end );
pair<iterator,bool> insert( const T& pair );

insert()関数は、次の動作をします。

  • “pos”で指定された要素の後に、要素”pair”を挿入します(挿入時には、”pos”が使われますが、すぐにマップは並び替えられます)。指定した要素”pair”を指すイテレータを返します。
  • イテレータの指す”start”から”end”までの要素を挿入します。
  • pair<key, val>の要素を挿入します。しかし、キーが重複する場合は挿入されません。戻り値は、挿入した要素のイテレータ(すでに要素がある場合はその要素を指す)と挿入できたかどうかの可否をboolで返します。

たとえば、次のコードは、関数の中で、make_pairを使い、いくつかのデータをマップに追加し、表示しています。

map<string,int> theMap;
theMap.insert( make_pair( "Key 1", -1 ) );
theMap.insert( make_pair( "Another key!", 32 ) );
theMap.insert( make_pair( "Key the Three", 66667 ) );
 
map<string,int>::iterator iter;
for( iter = theMap.begin(); iter != theMap.end(); ++iter ) {
  cout << "Key: '" << iter->first << "', Value: " << iter->second << endl;
}

上記のコードを実行すると以下の実行結果を得られます。

Key: 'Another key!', Value: 32
Key: 'Key 1', Value: -1
Key: 'Key the Three', Value: 66667

注:マップは、格納時に並べ替えられます、出力時にはキーで並べ替えられています。 例では、キーがstring型なので、アルファベット順に並べ替えされます。

Related Topics: [] operator

 
• • • SitemapRecent changesRSScc