fork download
  1.  
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5. #include <unordered_map>
  6.  
  7. template<typename T>
  8. class lookup {
  9. std::unordered_map<T, int> position;
  10. public:
  11. lookup(const std::vector<T>& a) {
  12. for(int i = 0; i < a.size(); ++i) position.emplace(a[i], i);
  13. }
  14. int operator()(const T& key) const {
  15. auto pos = position.find(key);
  16. return pos == position.end() ? -1 : pos->second;
  17. }
  18. };
  19.  
  20. template<typename T>
  21. static lookup<T> make_lookup(const std::vector<T>& a) {
  22. return lookup<T>(a);
  23. }
  24.  
  25. int main() {
  26. std::vector<std::string> foo{"a", "b", "d", "e", "g", "k", "m", "n", "r", "x"};
  27. auto find = make_lookup(foo);
  28. for(std::string key : {"g", "m", "p"}) {
  29. std::cout << find(key) << std::endl;
  30. }
  31. return 0;
  32. }
  33.  
  34.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
4
6
-1