unordered_set::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_set__unordered_set_insert.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::tr1::unordered_set<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents " [c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << " [" << *it << "]";
std::cout << std::endl;
// insert with hint and reinspect
Myset::iterator it2 = c1.insert(c1.begin(), 'd');
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << " [" << *it << "]";
std::cout << std::endl;
// insert range and inspect
Myset c2;
c2.insert(c1.begin(), c1.end());
for (Myset::const_iterator it = c2.begin();
it != c2.end(); ++it)
std::cout << " [" << *it << "]";
std::cout << std::endl;
// insert with checking and reinspect
std::pair<Myset::iterator, bool> pib =
c1.insert('e');
std::cout << "insert(['a',]) success == "
<< std::boolalpha << pib.second << std::endl;
pib = c1.insert('a');
std::cout << "insert(['a',]) success == "
<< std::boolalpha << pib.second << std::endl;
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << " [" << *it << "]";
std::cout << std::endl;
return (0);
}
[c] [b] [a]
[d] [c] [b] [a]
[d] [c] [b] [a]
insert(['a',]) success == true
insert(['a',]) success == false
[e] [d] [c] [b] [a]
必要条件
ヘッダー : <unordered_set>
名前空間 : std::tr1