std::copy算法

函数模板

std::copy

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

元素的复制范围

将范围[ first,last)中的元素复制到从 result 开始的范围中。

函数返回目标范围末尾的迭代器(它指向最后复制的元素之后的元素)。

这些范围不应该以这样的方式重叠,即结果指向范围[ first,last)中的一个元素。对于这种情况,请参见 copy_backward.


此函数模板的行为等效于:

template<class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = *first;
    ++result; ++first;
  }
  return result;
}

参数:

first, last

输入迭代器 到要复制的序列中的初始位置和最终位置。使用的范围是[ first,last) ,它包含第一个和最后一个之间的所有元素,包括由 first 指向的元素,但不包括由 last 指向的元素。

result

输出迭代器 到目标序列中的初始位置。这不应该指向范围[ first,last)中的任何元素。

返回值

到已复制元素的目标范围末尾的迭代器。

例子

// copy algorithm example
#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;
}


输出:

myvector contains: 10 20 30 40 50 60 70

附:

copy只负责复制,不负责申请空间,所以复制前必须有足够的空间。如果container的大小小于输入序列的长度N的话,这段代码会导致崩溃(crash)。所以此时引入了back_inserter,如下

std::copy(src.begin(), src.end(), std::back_inserter(dest));


标准库提供的back_inserter模板函数很方便,因为它为container返回一个back_insert_iterator迭代器,这样,复制的元素都被追加到container的末尾了。(就算container为空也没事)。

在本例中,另外一种可选方法是应用back_insert_iterator 作为目的参数。该迭代器扩展目的容器为每一次复制扩展元素,确保了容器有足够的大小来容纳每个元素。
 

附件参考:链接

猜你喜欢

转载自blog.csdn.net/weixin_58045467/article/details/130834164
std
今日推荐