Skip to content

Instantly share code, notes, and snippets.

@maraigue
Created July 7, 2014 13:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraigue/ee4ae42a04f7a2716870 to your computer and use it in GitHub Desktop.
Save maraigue/ee4ae42a04f7a2716870 to your computer and use it in GitHub Desktop.
[C++] std::mapのconst参照に対して要素を取得するときには at(key) が使えますよ、という話(C++11標準、gccはそれ以前から実装)
#include <map>
#include <iostream>
#include <stdexcept>
class MyClass{
public:
typedef std::map<int, int> storage_type;
private:
storage_type value_;
public:
MyClass(){
// ここは適当。実際は別の入力(ファイルの内容とか)に基づき
// 何らかの値をvalue_に格納する
value_[3] = 5;
value_[5] = 10;
value_[8] = 15;
}
// ここで返しているのがconst参照であることに注意
const storage_type & value() const{
return value_;
}
};
int main(void){
MyClass myc;
// こういうことをしたくなるのだが、実際はコンパイルエラー。
// map::operator[]はconst性を維持しない。
// ([]の中の値に対応する要素が存在しなければ「新規に作る」挙動のため)
//std::cout << myc.value()[8] << std::endl;
// C++03までの範囲ではこうする必要がある
MyClass::storage_type::const_iterator it;
it = myc.value().find(8);
std::cout << (it != myc.value().end() ? it->second : -1) << std::endl;
it = myc.value().find(10);
std::cout << (it != myc.value().end() ? it->second : -1) << std::endl;
// C++11以降ならこうすることもできる
// ※gccでは早くから非標準という断り書き付きで導入されていたため
//  -std=c++0x や -std=c++11 のオプションがなくてもコンパイルは通る
//  http://www.pakunet.jp/hoge/2006/12/17/1
try{
std::cout << myc.value().at(8) << std::endl;
}catch(const std::out_of_range & e){
std::cout << "Not Found" << std::endl;
}
try{
std::cout << myc.value().at(10) << std::endl;
}catch(const std::out_of_range & e){
std::cout << "Not Found" << std::endl;
}
}
// 実行結果
/*
15
-1
15
Not Found
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment