OutputIterator copy(InputIterator scourceBeg,InputIterator sourceEnd,
OutputIterator destBeg)
BidirectionalIterator1
copy_backward(BidirectionalIterator1 sourceBeg,BidirectionalIterator1 sourceEnd,
BidirectionalIterator2 destEnd)
- 这两个算法都将源区间[sourceBeg,sourceEnd)中的所有元素复制到以destBeg为起点或以destEnd为终点的目标区间
- 返回目标区间内最后一个被复制元素的下一位置,也就是第一个未被覆盖的元素的位置
- destBeg或destEnd不可处于[sourceBeg,sourceEnd)区间内
- copy()正向遍历序列,而copy_backward()逆向遍历序列
- 如果希望再复制过程中逆转元素次序,应使用reverse_copy(),该算法比“copy()算法搭配逆向迭代器”略快
- 调用者必须保证目标区间有足够空间,否则需要使用insert迭代器
现在我们举例看一下copy()算法的一些应用
#include<iostream>
#include<algorithm>
#include<vector>
#include<list>
#include<iterator>
using namespace std;
template <typename T>
void INSERT_ELEMENT(vector<T>& v, int a, int b)
{
for (int i = a; i <= b; ++i)
{
v.push_back(i);
}
}
int main()
{
vector<int> col1;
list<int> col2;
INSERT_ELEMENT(col1, 1, 9);
copy(col1.begin(), col1.end(), back_inserter(col2));//在末尾插入元素
copy(col2.begin(), col2.end(), ostream_iterator<int>(cout, " "));//打印元素
cout << endl;
copy(col1.rbegin(), col1.rend(), col2.begin());
copy(col2.begin(), col2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
运行结果如下
copy(col1.begin(), col1.end(), back_inserter(col2));
这一句代码中涉及到back_inserter()。back_inserter用于在末尾插入元素,其设计目的是避免容器中的原始元素被覆盖,在容器的末尾自动插入新元素。这一句代码的意思就是在col2的末尾添加元素,这些元素是从col1中col1.begin()至col1.end()中复制过来了,通过打印col2中的元素我们也可以看出来这一点。
下面这个例子展示copy()和copy_backward()之间的区别
#include<iostream>
#include<algorithm>
#include<vector>
#include<list>
#include<iterator>
using namespace std;
template <typename T>
void INSERT_ELEMENT(vector<T>& v, int a, int b)
{
for (int i = a; i <= b; ++i)
{
v.push_back(i);
}
}
int main()
{
//initialize source
vector<char> source(10, '.');
for (int c = 'a'; c <= 'f'; c++)
{
source.push_back(c);
}
source.insert(source.end(), 10, '.');
for (auto c : source)
{
cout << c;
}
cout << endl;
//copy all letters three elements in front of the 'a'
vector<char> c1(source.begin(), source.end());
copy(c1.begin() + 10, c1.begin() + 16, c1.begin() + 7);//以(c1.begin() + 7)为起点
for (auto c : c1)
{
cout << c;
}
cout << endl;
//copy all letters three elements behind the 'f'
vector<char> c2(source.begin(), source.end());
copy_backward(c2.begin() + 10, c2.begin() + 16, c2.begin() + 19);//以(c1.begin() + 19)为终点
for (auto c : c2)
{
cout << c;
}
}
程序运行结果
对于copy和copy_backward这两个算法,它们都是将区间[sourceBeg,sourceEnd)中的元素复制到以destBeg为起点或以destEnd为终点的目标区间去。