fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <string>
  5.  
  6. template<typename Key, typename Val>
  7. class OrderedMap
  8. {
  9. private:
  10. std::vector<std::pair<Key, Val>> ordered;
  11. std::map<Key, std::size_t> lookup;
  12.  
  13. public:
  14. void insert(Key k, Val v)
  15. {
  16. ordered.push_back(std::pair<Key, Val>(k, v));
  17. lookup.emplace(k, ordered.size() - 1);
  18. }
  19.  
  20. Val find(Key k)
  21. {
  22. std::size_t index = lookup[k];
  23. return ordered[index].second;
  24. }
  25.  
  26. // "typename" needed as the "iterator" is a dependent type
  27. typename std::vector<std::pair<Key, Val>>::iterator begin()
  28. {
  29. return ordered.begin();
  30. }
  31. typename std::vector<std::pair<Key, Val>>::iterator end()
  32. {
  33. return ordered.end();
  34. }
  35. };
  36.  
  37. int main()
  38. {
  39. OrderedMap<std::string, int> m;
  40. m.insert("1", 1);
  41. m.insert("2", 2);
  42. m.insert("3", 3);
  43.  
  44. std::cout << m.find("2") << std::endl << std::endl;
  45.  
  46. for (auto i = m.begin(); i != m.end(); i++)
  47. std::cout << i->first << " " << i->second << std::endl;
  48. std::cout << std::endl;
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0s 4560KB
stdin
Standard input is empty
stdout
2

1 1
2 2
3 3