for_each_assoc.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Range v3 library
  2. //
  3. // Copyright Jeff Garland 2017
  4. //
  5. // Use, modification and distribution is subject to the
  6. // Boost Software License, Version 1.0. (See accompanying
  7. // file LICENSE_1_0.txt or copy at
  8. // http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. // Project home: https://github.com/ericniebler/range-v3
  11. //
  12. ///[for_each_assoc]
  13. // for_each with associative containers
  14. // output
  15. // set: 1 2 3 4 5 6
  16. // map: one:1 three:3 two:2
  17. // unordered_map: three:3 one:1 two:2
  18. // unordered_set: 6 5 4 3 2 1
  19. #include <iostream>
  20. #include <map>
  21. #include <range/v3/algorithm/for_each.hpp>
  22. #include <set>
  23. #include <string>
  24. #include <unordered_map>
  25. #include <unordered_set>
  26. using std::cout;
  27. using std::string;
  28. auto print = [](int i) { cout << i << ' '; };
  29. // must take a pair for map types
  30. auto printm = [](std::pair<string, int> p) {
  31. cout << p.first << ":" << p.second << ' ';
  32. };
  33. int
  34. main()
  35. {
  36. cout << "set: ";
  37. std::set<int> si{1, 2, 3, 4, 5, 6};
  38. ranges::for_each(si, print);
  39. cout << "\nmap: ";
  40. std::map<string, int> msi{{"one", 1}, {"two", 2}, {"three", 3}};
  41. ranges::for_each(msi, printm);
  42. cout << "\nunordered map: ";
  43. std::unordered_map<string, int> umsi{{"one", 1}, {"two", 2}, {"three", 3}};
  44. ranges::for_each(umsi, printm);
  45. cout << "\nunordered set: ";
  46. std::unordered_set<int> usi{1, 2, 3, 4, 5, 6};
  47. ranges::for_each(usi, print);
  48. cout << '\n';
  49. }
  50. ///[for_each_assoc]