本文主要是介绍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 <iostream> // std::cout
#include <algorithm> // std::copy
#include <vector> // std::vectorint 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 <iostream> // std::cout
#include <iterator> // std::back_inserter
#include <vector> // std::vector
#include <algorithm> // std::copyint 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()的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!