unordered_mapは名前のとおり、keyの順序に関係なくHashを使って格納する。
keyの順序によってソートしたい場合は、std::map を使えば良い。
mapへの操作は、unordered_map も std::map も基本的に同じである。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// unordered_map.cpp | |
// CplusplusPractice | |
// | |
// Created by masai on 2015/05/20. | |
// Copyright (c) 2015年 masai. All rights reserved. | |
// | |
#include <iostream> | |
#include <unordered_map> | |
using namespace std; | |
int main(){ | |
// keyとvalueの型を指定して初期化する | |
unordered_map<string, int> hash; | |
// key testの追加 | |
hash["test"] = 10; | |
// key testのvalueを取得 | |
cout << hash["test"] << endl; | |
// 存在しないkeyを指定しても、領域が確保される | |
cout << hash["test2"] << endl; | |
// at()では、存在するkey test が使える。 | |
hash.at("test") = 20; | |
cout << hash.at("test") << endl; | |
// at()で、存在しないkey test2 を指定すると out_of_range例外が発生する | |
// hash.at("test2") = 30; NG | |
// keyとvalueをセットで追加したい場合、insertを使う | |
hash.insert(pair<string, int>("pair", 30)); | |
cout << hash.at("pair") << endl; | |
// 状態を取得する | |
cout << hash.size() << endl; | |
cout << hash.empty() << endl; | |
// iterator | |
unordered_map<string, int>::iterator it = hash.begin(); | |
while( it != hash.end() ) | |
{ | |
cout << (*it).first << ":" << (*it).second << endl; | |
++it; | |
} | |
return 0; | |
} |
http://program.station.ez-net.jp/special/handbook/cpp/stl/map.asp
0 件のコメント:
コメントを投稿