fork download
  1. #include <map>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <stdexcept>
  5.  
  6. //functor
  7. template<class key, class value>
  8. struct finder {
  9. finder(const value& value_to_find) : v(&value_to_find){}
  10. bool operator()(const std::pair<const key&, value>& node)
  11. {return node.second == *v;}
  12. protected:
  13. const value* v;
  14. };
  15.  
  16. template<class key, class value>
  17. const key& find_key(const std::map<key, value>& container, const value& value_to_find) {
  18. typename std::map<key, value>::const_iterator it;
  19. it = std::find_if(container.begin(), container.end(), finder<key, value>(value_to_find));
  20. if (it == container.end())
  21. throw std::runtime_error("value is not in container!");
  22. return it->first;
  23. }
  24.  
  25. int main() {
  26. std::map<int, int> container;
  27. container[3] = 7;
  28. std::cout << find_key(container, 7);
  29. }
Success #stdin #stdout 0.01s 2860KB
stdin
Standard input is empty
stdout
3