std::copy() & std::back_inserter()

std::copy

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

std::copy()函数和strcpy()的实现类似,只是参数类型由char 变为 iterator

// 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<int> myvector (7);//一定要初始化大小

  //这三个参数要记住
  std::copy ( myints, myints+7, myvector.begin() );
  //参数       first   last      result    
  // [first,last)

  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

std::back_inserter()

// back_inserter example
#include      // std::cout
#include      // std::back_inserter
#include        // std::vector
#include     // std::copy

int main () {
  std::vector<int> foo,bar;
  for (int i=1; i<=5; i++)
  { foo.push_back(i); bar.push_back(i*10); }

  std::copy (bar.begin(),bar.end(),back_inserter(foo));
//back_inserter() 把当前iterator插入到foo容器尾部,返回类型是一个叫back_insert_iterator的东西..

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

  return 0;
}
Output:

foo contains: 1 2 3 4 5 10 20 30 40 50

你可能感兴趣的:(std::copy() & std::back_inserter())