C++ 算法 中的 copy_if函数

首页 / C++入门教程 / C++ 算法 中的 copy_if函数

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入剖析Kubernetes -〔张磊〕

10x程序员工作法 -〔郑晔〕

重学前端 -〔程劭非(winter)〕

浏览器工作原理与实践 -〔李兵〕

设计模式之美 -〔王争〕

深入浅出云计算 -〔何恺铎〕

数据中台实战课 -〔郭忆〕

Go进阶 · 分布式爬虫实战 -〔郑建勋〕

Python实战 · 从0到1搭建直播视频平台 -〔Barry〕

好记忆不如烂笔头。留下您的足迹吧 :)