unordered_map::emplace学習

6796 ワード

Insertとemplaceの違いはさておき、emplaceだけを言います.emplaceはconstruct element in place without move or copyを許可する.forwardingとvariadic template(可変テンプレート)を使用してforward arguments to the constructor of the key-value pair.
template<class... Args>
std::pair<iterator,bool> emplace(Args&&... args);

 The constructor of the new element (i.e. std::pair) is called with exactly the same arguments as supplied to  emplace , forwarded via std::forward(args)....
上記のように、戻りタイプはpairであり、iteratorが挿入位置を指すことを含む.もし...firstのkeyはすでに存在し、挿入されず、keyが存在するiteratorを返します.戻るpair.secondはboolで挿入するかどうかを説明します.
Amortized屋台はまた複雑度が定数であり、最悪は線形複雑度である可能性がある.
// uses pair's move constructor
    m.emplace(std::make_pair(std::string("a"), std::string("a")));
 
    // uses pair's converting move constructor
    m.emplace(std::make_pair("b", "abcd"));
 
    // uses pair's template constructor
    m.emplace("d", "ddd");
 
    // uses pair's piecewise constructor
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple("c"),
              std::forward_as_tuple(10, 'c'));

Emplaceはin-placeの場合construct a map::value_type、つまりpairタイプです.上記のようにpecewiseを使用しない限りconstructとforward_as_tupleはpairタイプのmove/convert move/template constructorを使用します.
If either the key or the value needs more than one constructor argument, you’ll need forward_as_tuple.    std::[unordered_]map takes its first two template parameters and feeds them into std::pair to generate its map::value_type.
結論から言えば、empalceを使う過程でmake_を使うとpair(...),pairのタイプのmove操作が必要になりますが、piecewise_を使用するとconstruct, forward_as_tuple, forward_as_tupleでは、move操作のサポートは必要ありません.しかし、どちらの場合もdefault constructorを使用する必要があります.これはtuple側の必要です.
size(), max_size(), max_bucket_count(), bucket_count(), bucket_size(size_type n)はnumber of elements,max number of elements,max number of buckets,number of buckets(現在どれだけあるか)、number of elements in bucket n;自分で書いたhash tableにはbucket数とelements数の違いがあり、ここでは字面の意味で理解できる.そのうち最初の2つの戻り値は1つのプラットフォームの下で固定され、bucket_count()の値は、要素の数が増加するにつれて大きくなり、load factorがmax load factorより低くなる.load_factor()はfloat値を返し、現在のload factor=size()/bucket_を表します.count();max_load_factor()が再ロードされ、最大マウント係数を返して設定できます.デフォルトは1.0です.load_factorがmaxより大きいload_factorはrehash(size_type n)をもたらします.rehashは、再設定bucketsの数がn以上であるが、n max_load_factor自動トリガ.ここでrehash(size_type)のパラメータの意味はbuckets numberであり、関数reserve(size_type n)のパラメータの意味はbucketsの数を設定してn個のelements、すなわちパラメータがelementsの数であることである.関数bucket(const key_type&k)constは、kに対応するelementが存在するbucketの数を返します.
unordered_を巡りたいmapはiteratorsを使用し、begin()からend()まで使用します.あるいはfor(auto&x:mymap){