首页 > 代码库 > vector和list容器之间的复制

vector和list容器之间的复制


#include <iostream>
#include <list>
#include <string>
#include <vector>
#include <iterator>
using namespace std;

int main()
{
	//copy list to list
	list<string> oldList;
	list<string> newList;
	oldList.push_back("test1");
	oldList.push_back("test2");
	oldList.push_back("test3");
	copy(oldList.begin(), oldList.end(), back_inserter(newList));	

	//copy vector to vector
	vector<string> oldVector;
	vector<string> newVector;
	oldVector.push_back("test4");
	oldVector.push_back("test5");
	oldVector.push_back("test6");
	copy(oldVector.begin(), oldVector.end(), back_inserter(newVector));	

	//copy list to vector
	list<string> list1;
	vector<string> vector1;
	list1.push_back("test7");
	list1.push_back("test8");
	list1.push_back("test9");
	copy(list1.begin(), list1.end(), back_inserter(vector1));	

	//copy vector to list
	vector<string> vector2;
	list<string> list2;
	vector2.push_back("test10");
	vector2.push_back("test11");
	vector2.push_back("test12");
	copy(vector2.begin(), vector2.end(), back_inserter(list2));	

	return 0;
}

特别注意:

copy(vec.begin()+3, vec.begin()+6, back_inserter(list2));
这样的情况下,仅仅是拷贝了vec[3]、vec[4]、vec[5]  。

vec[6]并没有拷贝!

vector和list容器之间的复制