Back to TILs

C++ algorithm swap_range

Date: 2022-12-26Last modified: 2024-11-02

Table of contents

  std::vector<char> v = {'a', 'b', 'c', 'd', 'e'};
  std::list<char> l = {'1', '2', '3', '4', '5'};

  auto print = [](auto comment, auto const& seq) {
    std::cout << comment;
    for (const auto& e : seq) {
      std::cout << e << ' ';
    }
    std::cout << '\n';
  };

  print("Before swap_ranges:\nv: ", v);
  print("l: ", l);

  std::swap_ranges(v.begin(), v.begin() + 3, l.begin());

  print("After swap_ranges:\nv: ", v);
  print("l: ", l);

Possible output

Before swap_ranges:
v: a b c d e 
l: 1 2 3 4 5 
After swap_ranges:
v: 1 2 3 d e 
l: a b c 4 5