无涯教程-C++ 算法 - copy_if函数

77 阅读1分钟

C++算法copy_if()函数用于将集合[first,last]的元素复制到另一个集合中,该集合从pred值为true的结果开始。

copy_if - 语法

template<class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if(InputIterator first, InputIterator last, OutputIterator result,UnaryPredicate pred);

copy_if - 参数

first:它是参数的第一个元素的输入迭代器,其中元素本身包含在参数中。

last:它是参数最后一个元素的输入迭代器,其中元素本身不包含在参数中。

result:它是新集合中要复制元素的第一个元素的输出迭代器。

pred :这是一个Unary函数,它接受一个元素作为参数并检查指定的条件。

copy_if - 返回值

返回从结果开始到新参数的最后一个元素的迭代器。

copy_if - 例子1

#include<iostream>
#include<algorithm>
#include<vector>
int main()
{
	std::vector<int> a = {20,10, 4,-4,-10};
	std::vector<int> b (a.size());
	auto ti = std::copy_if(a.begin(),a.end(),b.begin(),[](int j){ return !(j<0);});
	b.resize(std::distance(b.begin(),ti));
	std::cout<<"b contains:";
	for (int& x:b) std::cout<<" "<<x;
	std::cout<<"\n";
	return 0;
}

输出:

b contains: 20 10 4

copy_if - 例子2

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
	vector<int> u1={2,6,7,4,9,4};
	vector<int> u2(6);
	copy_if(u1.begin(),  u1.end(), u2.begin(), [](int j){return j%2!=0;});
	cout<<"The new vector using copy_if contains:";
	for(int k=0; k<u2.size(); k++)
	cout<<u2[k]<<" ";
}

输出:

The new vector using copy_if contains:7 9 0 0 0 0

参考链接

www.learnfk.com/c++/cpp-alg…