STL 中的 remove_copy_if() 函数用于将前两个正向迭代器参数指定的序列中,能够使作为第 4 个参数的谓词返回 true 的元素,复制到第三个参数指定的目的序列中。
它返回一个指向最后一个被复制到目的序列的元素的后一个位置的迭代器。序列不能是重叠的。
#include <algorithm>
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator remove_copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);
参数 | 描述 |
---|---|
first | 输入迭代器 |
last | 输入迭代器 |
result | 输出迭代器 |
pred | 比较规则 |
使用 STL remove_copy_if 函数删除元素
#include<iostream>
#include<algorithm>
#include <vector>
using namespace std;
bool IsOdd (int i)
{
return ((i%2)==1);
}
int main()
{
std::cout << "嗨客网(www.haicoder.net)\n" << std::endl;
int myints[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> myvector (9);
std::remove_copy_if(myints, myints+9, myvector.begin(), IsOdd);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
{
std::cout << ' ' << *it;
}
std::cout << '\n';
return 0;
}
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ remove_copy_if.cpp -std=c++11
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们使用了 remove_copy_if 函数,实现了删除集合中的元素。
STL 中的 remove_copy_if() 函数用于将前两个正向迭代器参数指定的序列中,能够使作为第 4 个参数的谓词返回 true 的元素,复制到第三个参数指定的目的序列中。
它返回一个指向最后一个被复制到目的序列的元素的后一个位置的迭代器。序列不能是重叠的。