目录
int list[5] = {1, 3, 6, 9, 12}; vector<int> vList; copy(list,list+5,vList);
解决方法使用遍历数组,并调用push_back方法将元素保存到vList中。
另外一种比较好的方式是通过插入迭代器完成。
三种插入迭代器:back_inserter, front_inserter,inserter
示例代码:
#include <iostream> #include <list> #include <algorithm> #include <string> #include <numeric> #include <iterator> #include <vector> #include <functional> using namespace std; int main() { int lists[8] = {1,2,3,4,5,6,7,8}; vector<int> vList1; vector<int> vList2; ostream_iterator<int> screenOut(cout, " "); copy(lists,lists+8,back_inserter(vList1)); cout << "vList1:" << endl; copy(vList1.begin(),vList1.end(),screenOut); cout << endl; copy(vList1.begin(),vList1.end(),inserter(vList2,vList2.begin())); cout << "vList2:" << endl; copy(vList2.begin(),vList2.end(),screenOut); cout << endl; list<int> listTemp; copy(vList2.begin(),vList2.end(),front_inserter(listTemp)); cout << "listTemp:" << endl; copy(listTemp.begin(),listTemp.end(),screenOut); cout << endl; return 0; }
vList1:
1 2 3 4 5 6 7 8
vList2:
1 2 3 4 5 6 7 8
listTemp:
8 7 6 5 4 3 2 1