同一キーの要素を複数格納できず、格納順が規定されていないコンテナ

include

#include <unordered_map>

#include <iostream>
#include <unordered_map>
#include <iterator>
#include <algorithm>
#include <string>

template <class C>
void print(const C& c, std::ostream& os = std::cout)
{
  std::for_each(std::begin(c), std::end(c), [&os](typename C::value_type p) { os << '{' << p.first << ',' << p.second << "}, "; });
  os << std::endl;
}

int main()
{
  std::unordered_map<std::string, int> um{ {"1st", 1}, {"2nd", 2}, {"3rd", 3}, };

  print(um);

  std::cout << "3rd:" << um.at("3rd") << std::endl;

  um.emplace("4th", 4);

  print(um);

  um.erase("2nd");

  print(um);

  std::cout << "5th:" << um["5th"] << std::endl;

  print(um);
}
/*
{2nd,2}, {3rd,3}, {1st,1},
3rd:3
{4th,4}, {2nd,2}, {3rd,3}, {1st,1},
{4th,4}, {3rd,3}, {1st,1},
5th:0
{5th,0}, {4th,4}, {3rd,3}, {1st,1},
*/

キーの有無確認

C++17まで

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

int main() {
    unordered_map<string, int> table = {{ "one", 1 }, { "two", 2 }};

    // 意図が明快ではない
    if (table.find("one") != table.end())
        cout << "one というキーを持つ要素が存在\\n"; 
}

C++20

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

int main() {
    unordered_map<string, int> table = {{ "one", 1 }, { "two", 2 }};

    // 意図がわかりやすい
    if (table.contains("one"))
        cout << "one というキーを持つ要素が存在\\n";
}

参考文献

unordered_map - cpprefjp C++日本語リファレンス

連想コンテナ内のキーの有無の確認を .contains() で明快にしよう