fork download
  1. #include <iostream>
  2. #include <map>
  3.  
  4. int main()
  5. {
  6. // The value_type of a map is pair<const Key, T>.
  7. // To initialize a map an initializer list
  8. // of pair<Key, T> objects must be specified.
  9.  
  10. // To initialize a pair:
  11. //
  12. std::pair<int, int> p{9, 10};
  13. std::cout << "pair:\n (" << p.first << ", " << p.second << ")\n\n";
  14.  
  15. // To initialize a simple map (no nesting)
  16. // with value_type of pair<int, int>:
  17. //
  18. std::map<int, int> simple_map
  19. { // K V
  20. { 5, 6 },
  21. { 7, 8 }
  22. };
  23. std::cout << "simple_map:\n";
  24. for (auto const& i: simple_map)
  25. {
  26. std::cout << " (" << i.first << ", " << i.second << ")\n";
  27. }
  28. std::cout << "\n";
  29.  
  30. // To initialize a complex map (with nesting)
  31. // with value_type of pair<const int, map<int, int>>
  32. //
  33. const std::map<int, std::map<int, int>> complex_map
  34. { // K V
  35. // k v
  36. { 1, { {3, 4},
  37. {5, 6} }
  38. },
  39. { 2, { {7, 8},
  40. {8, 8},
  41. {9, 0} }
  42. }
  43. };
  44.  
  45. std::cout << "complex_map:\n";
  46. for (auto const& mi: complex_map)
  47. {
  48. std::cout << " (" << mi.first << ", ";
  49. for (auto const& p: mi.second)
  50. {
  51. std::cout << '(' << p.first << ", " << p.second << ')';
  52. }
  53. std::cout << ")\n";
  54. }
  55. }
  56.  
Success #stdin #stdout 0s 3036KB
stdin
Standard input is empty
stdout
pair:
  (9, 10)

simple_map:
  (5, 6)
  (7, 8)

complex_map:
  (1, (3, 4)(5, 6))
  (2, (7, 8)(8, 8)(9, 0))