Last active
August 29, 2015 14:21
-
-
Save MasazI/91afff2195b01f91e9e0 to your computer and use it in GitHub Desktop.
unordered_map.cpp
This file contains hidden or 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment