C++ 算法 中的 copy_n函数

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

C++算法copy_n()函数指定要复制到新集合中的元素数。该函数用于将集合[first,last)的n个元素从结果开始复制到另一个集合中。

copy_n - 语法

template<class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n(InputIterator first, Size n, OutputIterator result);

copy_n - 参数

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

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

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

copy_n - 返回值

返回以result为开头的新参数的最后一个元素的迭代器。

copy_n - 例子1

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
	vector<int> u1 = {2,6,8,4,9,4};
	vector<int> u2(6);
	vector<int> u3(6);
	copy(u1.begin(), u1.begin()+3, u2.begin());
	cout<<"The new vector with copy contains:";
	for(int k=0; k<u2.size(); k++)
	cout<<u2[k]<<" ";
	copy_n(u1.begin(),4,u3.begin());
	cout<<"\n";
	cout<<"The new vector using copy_n contains:";
	for(int m=0; m<u3.size(); m++)
	cout<<u3[m]<<" ";
}

输出:

The new vector with copy contains: 2 6 8 0 0 0 
The new vector using copy_n contains:2 6 8 4 0 0

copy_n - 例子2

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
	int newints[]={15,25,35,45,55,65,75};
	std::vector<int> newvector;
	newvector.resize(7);
	std::copy_n(newints,7,newvector.begin());
	std::cout<<"newvector contains:";
	for(std::vector<int>::iterator  ti= newvector.begin(); ti!=newvector.end();++ti)
	std::cout<<" "<<*ti;
	std::cout<<"\n";
	return 0;
}

输出:

newvector contains: 15 25 35 45 55 65 75

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

技术教程推荐

技术与商业案例解读 -〔徐飞〕

Service Mesh实践指南 -〔周晶〕

如何设计一个秒杀系统 -〔许令波〕

编译原理之美 -〔宫文学〕

手把手教你玩音乐 -〔邓柯〕

PyTorch深度学习实战 -〔方远〕

去无方向的信 -〔小麥〕

遗留系统现代化实战 -〔姚琪琳〕

超级访谈:对话玉伯 -〔玉伯〕

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