fork download
  1. #include <iostream>
  2. #include <set>
  3. #include <functional>
  4.  
  5. struct HeavyObject {
  6. HeavyObject(int x) : x{x} {}
  7. HeavyObject(const HeavyObject& r) : x(r.x) { std::cout << "copy\n"; }
  8.  
  9. bool operator<(const HeavyObject& r) const
  10. {
  11. return x < r.x;
  12. }
  13.  
  14. int x;
  15. };
  16.  
  17. bool operator<(const std::reference_wrapper<const HeavyObject>& l, const std::reference_wrapper<const HeavyObject>& r)
  18. {
  19. return l.get().x < r.get().x;
  20. }
  21.  
  22.  
  23. std::ostream& operator<<(std::ostream& out, const HeavyObject& o)
  24. {
  25. return out << o.x;
  26. }
  27.  
  28.  
  29.  
  30. template<typename T>
  31. void func(std::set<T>& s)
  32. {
  33. for (auto& el : s) {
  34. std::cout << el << " ";
  35. }
  36. }
  37.  
  38. int main()
  39. {
  40. std::set<HeavyObject> bigset;
  41. for (int i = 0; i < 5; ++i) {
  42. bigset.emplace(i);
  43. }
  44.  
  45. auto newEnd = bigset.begin();
  46. std::advance(newEnd, 3);
  47. std::set<std::reference_wrapper<const HeavyObject>> c;
  48. std::copy(bigset.begin(), newEnd, std::inserter(c, c.begin()));
  49. func(c);
  50. }
  51.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
0 1 2