使用一个东西,不明白它的道理,不高明
——侯捷老师
1.move()
功能:将一个序列里的元素移动到另一个序列里。
1.1 函数声明
template
OutputIterator move (InputIterator first, InputIterator last, OutputIterator result);
1.2 等价操作实现
template
OutputIterator move (InputIterator first, InputIterator last, OutputIterator result) {
while (first != last) {
*result = std::move(*first);
++result;
++first;
}
return result;
}
1.3 示例程式
void test_move() {
std::vector foo = {"air","water","fire","earth"};
std::vector bar (4);
// moving ranges:
std::cout << "Moving ranges...\n";
std::move ( foo.begin(), foo.begin()+4, bar.begin() );
std::cout << "foo contains " << foo.size() << " elements:";
std::cout << " (each in an unspecified but valid state)";
std::cout << '\n';
std::cout << "bar contains " << bar.size() << " elements:";
for (std::string& x: bar) std::cout << " [" << x << "]";
std::cout << '\n';
// moving container:
std::cout << "Moving container...\n";
foo = std::move (bar);
std::cout << "foo contains " << foo.size() << " elements:";
for (std::string& x: foo) std::cout << " [" << x << "]";
std::cout << '\n';
std::cout << "bar is in an unspecified but valid state";
std::cout << '\n';
}
1.4 参考链接
http://www.cplusplus.com/reference/algorithm/move/
2. move_backward()函数
2.1 函数声明
template
BidirectionalIterator2 move_backward (BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result);
2.2等价操作实现
template
BidirectionalIterator2 move_backward ( BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result )
{
while (last!=first) *(--result) = std::move(*(--last));
return result;
}
2.3示例程式
void test_move_forward() {
std::string elems[10] = {"air", "water", "fire", "earth"};
string strs[5];
// insert new element at the begining
std::move_backward(elems, elems+4, strs+4);
std::cout << strs[0] << endl;
std::cout << "strs contains: ";
for (auto& x : strs) {
cout << x << " ";
}
cout << endl;
for (int i = 0; i < 5; i++) {
cout << i << " " << strs[i] << " ";
}
cout << endl;
}
输出结果:
air
strs contains: air water fire earth
0 air 1 water 2 fire 3 earth 4
2.3 参考链接
http://www.cplusplus.com/reference/algorithm/move_backward/?kw=move_backward