C++ reference: copy

本文详细介绍了C++标准模板库(STL)中copy函数的使用方法,包括其语法、参数说明及返回值。通过一个具体的示例展示了如何将数组中的元素复制到vector容器中,适合初学者和C++开发者快速掌握并应用此函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考自:http://www.cplusplus.com/reference/algorithm/copy/

copy


#include<algorithm>
template <class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);

将范围[first,last)中的元素复制到从result开始的位置。返回一个迭代器指向目标范围的末尾(即复制的最后一个元素的后面)。

  •  实现
template<class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = *first;
    ++result; ++first;
  }
  return result;
}
  •  示例
#include <iostream>     // std::cout
#include <algorithm>    // std::copy
#include <vector>       // std::vector

int main () {
  int myints[]={10,20,30,40,50,60,70};
  std::vector<int> myvector (7);

  std::copy ( myints, myints+7, myvector.begin() );

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;

  std::cout << '\n';

  return 0;
}/*Output
myvector contains: 10 20 30 40 50 60 70
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值