C++进阶:STL算法10--复制

1. 简介

函数 作用 文档
copy(beg,end,res) 复制[beg,end)到res copy()
copy_backward(beg,end,res) copy()相同,不过元素是以相反顺序被拷贝。 copy_backward()

2. 示例代码

  • copy
// copy algorithm example
#include      // std::cout
#include     // std::copy
#include        // std::vector

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

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

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

  std::cout << '\n';

  return 0;
}
  • copy_backward
// copy_backward example
#include      // std::cout
#include     // std::copy_backward
#include        // std::vector

int main () {
  std::vector myvector;

  // set some values:
  for (int i=1; i<=5; i++)
    myvector.push_back(i*10);          // myvector: 10 20 30 40 50

  myvector.resize(myvector.size()+3);  // allocate space for 3 more elements

  std::copy_backward ( myvector.begin(), myvector.begin()+5, myvector.end() );

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

  return 0;
}

3. 练习

你可能感兴趣的:(C++进阶:STL算法10--复制)