「std::tr1::unordered map」の版間の差分

提供: C++入門
移動: 案内検索
(mapとhash_mapの違い)
行13: 行13:
 
* hash_mapは、==演算子とハッシュ関数が必要
 
* hash_mapは、==演算子とハッシュ関数が必要
 
* mapとhash_mapは、空間と時間のトレードオフ
 
* mapとhash_mapは、空間と時間のトレードオフ
* mapは、[[二分木]]
+
* mapは、二分木
  
 
== ヘッダファイル ==
 
== ヘッダファイル ==

2015年11月8日 (日) 15:05時点における版

std::tr1::unordered_map とは、キーを登録した順番とは関係なく、連想ハッシュです。キーを順番通りに格納する場合は、std::map を使用します。

読み方

std::tr1::unordered_map
えすてぃーでぃー てぃーあーるわん あんおーだーど まっぷ

概要

std::tr1::unordered_map は、 C++11 で追加されました。 hash_mapは、非推奨であるため、unordered_mapを使用します。

mapとhash_mapの違い

  • mapは、要素型を対象とする<演算子が必要
  • hash_mapは、==演算子とハッシュ関数が必要
  • mapとhash_mapは、空間と時間のトレードオフ
  • mapは、二分木

ヘッダファイル

#include <tr1/unordered_map>


単純な例 ハッシュとダンプの例

ソースコード umap1.cpp

#include <iostream>
#include <tr1/unordered_map>
using namespace std;
int
main(int argc, char const* argv[])
{
        std::tr1::unordered_map<std::string, int> hash;
 
        hash ["c"] = 3;
        hash ["a"] = 1;
        hash ["b"] = 2;
 
        for (auto& x: hash) {
                std::cout << x.first << ": " << x.second << std::endl;
        }
 
        return 0;
}

コンパイル

clang++ -std=c++11  umap1.cpp -o umap1

実行例

% ./umap1
a: 1
c: 3
b: 2

代入の順番

代入の順番をこのように変更したとしても、 umap1.cpp と同じ結果になります。

hash ["a"] = 1;
hash ["b"] = 2;
hash ["c"] = 3;

キーを追加した順番に依存せずに並んでいることがわかります。

% ./a.out
a: 1
c: 3
b: 2

キーを削除する例

ソースコード umap2.cpp

#include <iostream>
#include <tr1/unordered_map>
using namespace std;
 
int
main(int argc, char const* argv[])
{
        std::tr1::unordered_map<std::string, int> hash;
 
        hash ["c"] = 3;
        hash ["a"] = 1;
        hash ["b"] = 2;
        //hash ["a"] = 11;
 
        hash.erase ("a");
        hash.erase ("a"); // 2回あっても何も言われない。
 
        for (auto& x: hash) {
                std::cout << x.first << ": " << x.second << std::endl;
        }
 
        return 0;
}

コンパイル

clang++ -std=c++11  umap2.cpp -o umap2

実行例

% ./umap2
c: 3
b: 2

関連項目

シーケンスコンテナ

連想コンテナ

連行コンテナ 順不同

コンテナアダプタ

コンテナへのアクセスで利用

コンテナで役立つC++11以降の機能