# Standard Library Range Move AlgorithmsRange Move AlgorithmsMove

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`moveC++11 ``````#include <vector>
#include <iostream>
#include <algorithm>

int main () {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) { std::cout << x << ' '; }  // A B C D E
std::cout << '\n';
}``````
``````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}}`````` ``````#include <vector>
#include <iostream>
#include <algorithm>

int main () {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 << ' '; });
std::cout << '\n';
}``````

## `move_backward`move_backwardC++11 ``````#include <vector>
#include <iostream>
#include <algorithm>

int main () {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) { std::cout << x <<' '; }  // A B C D E
std::cout << '\n';
}`````` ``````#include <vector>
#include <iostream>
#include <algorithm>

int main () {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) { std::cout << x <<' '; }  // A B C D E
std::cout << '\n';
}``````

## `swap_ranges`swap_ranges ``````#include <vector>
#include <iostream>
#include <algorithm>

int main () {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) { std::cout << x <<' '; }  // 0 8 7 6 5 5
std::cout << '\n';
for (int x : r2) { std::cout << x <<' '; }  // 9 1 2 3 4 3 1
std::cout << '\n';
}`````` ``````#include <vector>
#include <iostream>
#include <algorithm>

int main () {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) { std::cout << x <<' '; }  // 8 7 6 5
std::cout << '\n';
for (int x : range2) { std::cout << x <<' '; }  // 1 2 3 4 9 9
std::cout << '\n';
}``````