fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <iterator>
  4. #include <map>
  5. #include <string>
  6. #include <tuple>
  7.  
  8. using container_type = std::multimap<std::string, int>;
  9.  
  10. std::multimap<std::string, int> original_table =
  11. {
  12. {"a", 1},
  13. {"c", 2},
  14. {"b", 3},
  15. {"b", 4},
  16. {"a", 5},
  17. {"b", 6}
  18. };
  19.  
  20. void unique(container_type& container)
  21. {
  22. for (auto iter = begin(container); iter != end(container); ++iter)
  23. {
  24. auto last = container.upper_bound(iter->first);
  25. container.erase(next(iter), last);
  26. }
  27. }
  28.  
  29. template <typename container_t>
  30. void print_associative(const container_t& c)
  31. {
  32. for (auto& item : c)
  33. std::cout << item.first << ": " << item.second << '\n';
  34. }
  35.  
  36. int main()
  37. {
  38. container_type table(original_table);
  39.  
  40. std::cout << "Before:\n";
  41. print_associative(table);
  42.  
  43.  
  44. unique(table);
  45. std::cout << "\nAfter:\n";
  46. print_associative(table);
  47.  
  48.  
  49. using key_type = container_type::key_type;
  50. using mapped_type = container_type::mapped_type;
  51. std::map<key_type, mapped_type> m(begin(original_table), end(original_table));
  52.  
  53. std::cout << "\nMap:\n";
  54. print_associative(m);
  55.  
  56. using value_type = container_type::value_type;
  57. auto value_equal = [](value_type& a, value_type&b) { return a.first == b.first; };
  58.  
  59. container_type unique_copy_result;
  60. std::unique_copy(begin(original_table), end(original_table),
  61. std::inserter(unique_copy_result, begin(unique_copy_result)),
  62. value_equal);
  63.  
  64. std::cout << "\nUnique_copy:\n";
  65. print_associative(unique_copy_result);
  66. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Before:
a: 1
a: 5
b: 3
b: 4
b: 6
c: 2

After:
a: 1
b: 3
c: 2

Map:
a: 1
b: 3
c: 2

Unique_copy:
a: 1
b: 3
c: 2