Standard Library Range Move Algorithms Range Move Algorithms Move

    This means that, e.g., target containers must be resized properly.

    Standard algorithms don't – and in most cases can't – check if the target range is large enough.

    Trying to copy elements beyond the target's capacity will invoke undefined behavior!

    move move C++11

    using lines_t = std::vector<std::string>;
    lines_t src {"X","Y","A","B","C","D","E","F","G"};
    lines_t tgt;
    tgt.resize(5);
    move(begin(src)+2, begin(src)+7, begin(tgt));
    for (auto const& x : tgt) { cout << x << ' '; }  // A B C D E
    
    using X = std::vector<std::vector<int>>;
    X v {{1,2,3}, {4,5}, {7,8}};
    X w; w.resize(2);
    
    move(begin(v)+1, end(v), begin(w));
    v.erase(begin(v)+1, end(v));
    
    v: {{1,2,3},{4,5},{7,8}}
    w: {{},{}}
    
    v: {{1,2,3},{},{}} w: {{4,5},{7,8}}
    v: {{1,2,3}}
    using lines_t = std::vector<std::string>;
    lines_t src {"A","B","C","D","E"};
    lines_t tgt;
    tgt.resize(8);
    auto ends = std::ranges::move(src, begin(tgt)+1);
    for_each(begin(tgt)+1, ends.out, [](auto const& x) { 
      std::cout << x << ' '; });
    

    move_backward move_backward C++11

    using lines_t = std::vector<std::string>;
    lines_t src {"X","Y","A","B","C","D","E","F"};
    lines_t tgt;
    tgt.resize(5);
    move_backward(begin(src)+2, begin(src)+7, end(tgt));
    for (auto const& x : tgt) { cout << x <<' '; }  // A B C D E
    
    using lines_t = std::vector<std::string>;
    lines_t src {"A","B","C","D","E"};
    lines_t tgt;
    tgt.resize(7);
    auto ends = std::ranges::move_backward(src, end(tgt));
    for (auto const& x : tgt) { cout << x <<' '; }  // A B C D E
    

    swap_ranges swap_ranges

    std::vector<int> r1 {0,1,2,3,4,5};
    std::vector<int> r2 {9,8,7,6,5,3,1};
    // swap subranges (as shown in image):
    swap_ranges(begin(r1)+1, begin(r1)+5, begin(r2)+1);
    for (int x : r1) { cout << x <<' '; }  // 0 8 7 6 5 5
    for (int x : r2) { cout << x <<' '; }  // 9 1 2 3 4 3 1
    
    std::vector<int> range1 {1,2,3,4};
    std::vector<int> range2 {8,7,6,5,9,9};
    std::ranges::swap_ranges(range1, range2);
    for (int x : range1) { cout << x <<' '; }  // 8 7 6 5
    for (int x : range2) { cout << x <<' '; }  // 1 2 3 4 9 9