fork download
  1. #include <utility>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <string>
  5. #include <iostream>
  6.  
  7. template <typename container_type>
  8. typename container_type::iterator find_by_key(container_type& container,
  9. const typename container_type::value_type::first_type& key)
  10. {
  11. typedef typename container_type::value_type element_type;
  12.  
  13. return std::find_if(std::begin(container), std::end(container),
  14. [&](const element_type& k) { return key == k.first; });
  15. }
  16.  
  17. int main()
  18. {
  19. typedef std::pair<unsigned, std::string> element_type;
  20.  
  21. std::vector<element_type> v =
  22. {
  23. { 1, "One" },
  24. { 3, "Three" },
  25. { 5, "Five" },
  26. { 7, "Seven" },
  27. { 9, "Nine" },
  28. { 10, "Ten" },
  29. { 8, "Eight" },
  30. { 6, "Six" },
  31. { 4, "Four" },
  32. { 2, "Two" }
  33. };
  34.  
  35. std::cout << "By key:\n";
  36. for (unsigned i = 1; i < 11; ++i)
  37. {
  38. std::vector<element_type>::iterator it = find_by_key(v, i);
  39.  
  40. std::cout << '\t' << i << " | ";
  41.  
  42. if (it != v.end())
  43. std::cout << it->second << '\n';
  44. else
  45. std::cout << "(null)\n";
  46. }
  47.  
  48. std::cout << "\n\nBy position:\n";
  49. for (unsigned i = 0; i < v.size(); ++i)
  50. {
  51. std::cout << "\tpos: " << i << ": " ;
  52. std::cout << v[i].first << " | " << v[i].second << '\n';
  53. }
  54. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
By key:
	1 | One
	2 | Two
	3 | Three
	4 | Four
	5 | Five
	6 | Six
	7 | Seven
	8 | Eight
	9 | Nine
	10 | Ten


By position:
	pos: 0: 1 | One
	pos: 1: 3 | Three
	pos: 2: 5 | Five
	pos: 3: 7 | Seven
	pos: 4: 9 | Nine
	pos: 5: 10 | Ten
	pos: 6: 8 | Eight
	pos: 7: 6 | Six
	pos: 8: 4 | Four
	pos: 9: 2 | Two