STL 中的 reverse_copy() 算法可以将源序列复制到目的序列中,目的序列中的元素是逆序的。定义源序列的前两个迭代器参数必须是双向迭代器。
目的序列由第三个参数指定,它是目的序列的开始迭代器,也是一个输出迭代器。如果序列是重叠的,函数的行为是未定义的。这个算法会返回一个输出迭代器,它指向目的序列最后一个元素的下一个位置。
#include <algorithm>
template <class BidirectionalIterator, class OutputIterator>
OutputIterator reverse_copy ( BidirectionalIterator first,
BidirectionalIterator last, OutputIterator result );
参数 | 描述 |
---|---|
first | 输入迭代器 |
last | 输入迭代器 |
result | 指出复制到目标区间的具体位置 |
返回一个迭代器,指出已被复制元素区间的起始位置。
使用 STL reverse_copy 函数拷贝集合
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
std::cout << "嗨客网(www.haicoder.net)\n" << std::endl;
int a[50];
int b[50];
for (int i = 0; i < 10; i++)
{
a[i] = i;
if (i != 9)
{
cout << a[i] << " ";
}
else
{
cout << a[i] << endl;
}
}
reverse(a, a+10);
for (int i = 0; i < 10; i++)
{
if (i != 9)
{
cout << a[i] << " ";
}
else
{
cout << a[i] << endl;
}
}
reverse_copy(a, a+10, b);
for (int i = 0; i < 10; i++)
{
if (i != 9)
{
cout << b[i] << " ";
}
else
{
cout << b[i] << endl;
}
}
return 0;
}
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ reverse_copy.cpp -std=c++11
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们使用了 reverse_copy 函数,实现了集合的拷贝。
STL 中的 reverse_copy() 算法可以将源序列复制到目的序列中,目的序列中的元素是逆序的。定义源序列的前两个迭代器参数必须是双向迭代器。