unordered_mapを使用しただけで、学びましょう。
名前が示すように、これはソートされていないマップ構造です。
テンプレートは次のように定義されています。
template < class Key, // unordered_map::key_type
class T, // unordered_map::mapped_type
class Hash = hash<Key>, // unordered_map::hasher
class Pred = equal_to<Key>, // unordered_map::key_equal
class Alloc = allocator< pair<const Key,T> > // unordered_map::allocator_type
> class unordered_map;
キーと値のペア、ハッシュルール、比較ルールを含め、アロケータオブジェクトのタイプを指定します。
内部的には、unorder_mapの要素は、キーまたはマップされた値の特定の順序に従って並べ替えられませんが、ハッシュ値に従ってバケットに編成され、キー値を介して個々の要素に直接かつ迅速にアクセスできるようになります(平均時間計算量)定数)。
unordered_mapを作成するには、次の4つの方法があります
。1、空の作成
2、コピーの作成
3、移動の作成
4、範囲の作成
5、初期値の作成
公式のサンプルコードを見て理解しましょう。
// constructing unordered_maps
#include <iostream>
#include <string>
#include <unordered_map>
typedef std::unordered_map<std::string,std::string> stringmap;
stringmap merge (stringmap a,stringmap b) {
stringmap temp(a); temp.insert(b.begin(),b.end()); return temp;
}
int main ()
{
stringmap first; // empty
stringmap second ( {
{
"apple","red"},{
"lemon","yellow"}} ); // init list
stringmap third ( {
{
"orange","orange"},{
"strawberry","red"}} ); // init list
stringmap fourth (second); // copy
stringmap fifth (merge(third,fourth)); // move
stringmap sixth (fifth.begin(),fifth.end()); // range
std::cout << "sixth contains:";
for (auto& x: sixth) std::cout << " " << x.first << ":" << x.second;
std::cout << std::endl;
return 0;
}
関数 | 特徴 |
---|---|
ベギン | 最初のキーと値のペアの順方向イテレータを返します |
終わり | 最後のキーと値のペアの後の位置の順方向イテレータを返します |
cbegin | beginと同じですが、const属性が追加されているため、返されたイテレータを使用してコンテンツを変更することはできません。 |
いくつか | endと同じですが、const属性が追加されているため、返されたイテレータを使用してコンテンツを変更することはできません。 |
空の | 空の場合はtrueを返し、それ以外の場合はfalseを返します |
サイズ | キーと値のペアの数を返します |
max_size | 収容できるキーと値のペアの最大数を返します。異なるシステムの結果は異なります。 |
オペレーター[キー] | 配列のように添え字で操作できます。現在の添え字にキーペア値がない場合は、新しいキーペア値を挿入します。 |
アットマーク) | キーに対応する値を返します。存在しない場合は、out_of_range例外を返します。 |
前任者がunordered_mapで踏んだピット:unordered_mapのピット
詳細については、公式Webサイトにアクセスして、STL:unordered_map
またはプログラミングネットワークを参照してください。