fork(1) download
  1. #include <string>
  2. #include <iostream>
  3. #include <vector>
  4. #include <map>
  5. #include <unordered_map>
  6. using namespace std;
  7.  
  8. template<template <typename...> class MAP, class KEY, class VALUE>
  9. std::vector<KEY>
  10. keys(const MAP<KEY, VALUE>& map)
  11. {
  12. std::vector<KEY> result;
  13. result.reserve(map.size());
  14. for(const auto& it : map){
  15. result.emplace_back(it.first);
  16. }
  17. return result;
  18. }
  19.  
  20. template<template <typename...> class MAP, class KEY, class VALUE>
  21. std::vector<VALUE>
  22. values(const MAP<KEY, VALUE>& map)
  23. {
  24. std::vector<VALUE> result;
  25. result.reserve(map.size());
  26. for(const auto& it : map){
  27. result.emplace_back(it.second);
  28. }
  29. return result;
  30. }
  31.  
  32. int main() {
  33. std::map<std::string, int> string_to_int;
  34. // std::unordered_map<std::string, int> string_to_int;
  35. string_to_int.emplace("foo", 12);
  36. string_to_int.emplace("bar", 34);
  37.  
  38. cout << "Keys:" << endl;
  39. for(const auto& k : keys(string_to_int)){
  40. cout << k << endl;
  41. }
  42.  
  43. cout << "Values:" << endl;
  44. for(const auto& v : values(string_to_int)){
  45. cout << v << endl;
  46. }
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Keys:
bar
foo
Values:
34
12