unordered_map::insert

更新 : 2007 年 11 月

要素を追加します。

std::pair<iterator, bool> insert(const value_type& val);
iterator insert(iterator where, const value_type& val);
template<class InIt>
    void insert(InIt first, InIt last);

パラメータ

  • InIt
    反復子の型。

  • first
    挿入する範囲の最初。

  • last
    挿入する範囲の最後。

  • val
    挿入する値。

  • where
    コンテナ内の挿入位置 (ヒントのみ)。

解説

1 つ目のメンバ関数は、キーの大小関係が val と同じである要素 X がシーケンス内に存在するかどうかを調べます。存在しなかった場合は、それに該当する要素 X を作成し、val で初期化します。この関数は、さらに、X を指定する反復子 where を調べます。挿入が行われた場合は、std::pair(where, true) を返します。それ以外の場合は、std::pair(where, false) を返します。

2 つ目のメンバ関数は、被制御シーケンス内の挿入位置の検索開始位置として where を使用して、insert(val).first を返します。挿入位置が where の直前または直後である場合、挿入処理が若干速くなる可能性があります。3 つ目のメンバ関数は、範囲 [first, last) 内の各 where について、insert(*where) を呼び出すことによって、要素値のシーケンスを挿入します。

単一要素の挿入時に例外がスローされた場合、コンテナは変更されず、再度例外がスローされます。複数要素の挿入時に例外がスローされた場合、コンテナは安定してはいるものの未指定の状態になり、再度例外がスローされます。

使用例

 

// std_tr1__unordered_map__unordered_map_insert.cpp 
// compile with: /EHsc 
#include <unordered_map> 
#include <iostream> 
 
typedef std::tr1::unordered_map<char, int> Mymap; 
int main() 
    { 
    Mymap c1; 
 
    c1.insert(Mymap::value_type('a', 1)); 
    c1.insert(Mymap::value_type('b', 2)); 
    c1.insert(Mymap::value_type('c', 3)); 
 
// display contents " [c 3] [b 2] [a 1]" 
    for (Mymap::const_iterator it = c1.begin(); 
        it != c1.end(); ++it) 
        std::cout << " [" << it->first << ", " << it->second << "]"; 
    std::cout << std::endl; 
 
// insert with hint and reinspect 
    Mymap::iterator it2 = c1.insert(c1.begin(), Mymap::value_type('d', 4)); 
    for (Mymap::const_iterator it = c1.begin(); 
        it != c1.end(); ++it) 
        std::cout << " [" << it->first << ", " << it->second << "]"; 
    std::cout << std::endl; 
 
// insert range and inspect 
    Mymap c2; 
 
    c2.insert(c1.begin(), c1.end()); 
    for (Mymap::const_iterator it = c2.begin(); 
        it != c2.end(); ++it) 
        std::cout << " [" << it->first << ", " << it->second << "]"; 
    std::cout << std::endl; 
 
// insert with checking and reinspect 
    std::pair<Mymap::iterator, bool> pib = 
        c1.insert(Mymap::value_type('e', 5)); 
    std::cout << "insert(['a', 5]) success == " 
        << std::boolalpha << pib.second << std::endl; 
    pib = c1.insert(Mymap::value_type('a', 6)); 
    std::cout << "insert(['a', 5]) success == " 
        << std::boolalpha << pib.second << std::endl; 
    for (Mymap::const_iterator it = c1.begin(); 
        it != c1.end(); ++it) 
        std::cout << " [" << it->first << ", " << it->second << "]"; 
    std::cout << std::endl; 
 
    return (0); 
    } 
 
 [c, 3] [b, 2] [a, 1]
 [d, 4] [c, 3] [b, 2] [a, 1]
 [d, 4] [c, 3] [b, 2] [a, 1]
insert(['a', 5]) success == true
insert(['a', 5]) success == false
 [e, 5] [d, 4] [c, 3] [b, 2] [a, 1]

必要条件

ヘッダー : <unordered_map>

名前空間 : std::tr1

参照

参照

<unordered_map>

unordered_map クラス