C++ Wiki

2015.07.31

Tags: STL

std::mapの使い方

サンプルコード

#include <iostream>
#include <map>
#include <string>

int main()
{
  std::map<std::string, int> map;

  map["abc"] = 1;
  map["aaa"] = 2;
  map["bbb"] = 3;

  std::cout << "map[\"aaa\"] = " << map["aaa"] << std::endl;

  std::map<std::string, int>::const_iterator iter = map.find("bbb");
  std::cout << "map[\"bbb\"] = " << iter->second << std::endl;

  iter = map.find("ccc");
  if(iter != map.end()){
    std::cout << "map[\"ccc\"] = " << iter->second << std::endl;
  }
  else{
    std::cout << "map[\"ccc\"]: not found" << std::endl;
  }

  return 0;
}

実行結果

map["aaa"] = 1
map["bbb"] = 2
map["ccc"]: not found