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

提供: C++入門
移動: 案内検索
(関連項目)
行123: 行123:
 
== 関連項目 ==
 
== 関連項目 ==
 
* [[std::map]]
 
* [[std::map]]
 +
* [[auto]]
 
<!-- vim: filetype=mediawiki -->
 
<!-- vim: filetype=mediawiki -->

2013年12月26日 (木) 01:17時点における版

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

関連項目