C++标准库---advance应用于各容器

下面对advance()算法应用于不同容器进行测试,advance支持所有标准容器。

//STL---advance()测试
#include<set>
#include<vector>
#include<list>
#include<deque>
#include<map>
#include<algorithm>
#include<iterator>
#include<iostream>
#include<string>

using namespace std;

int main()
{
	//vector测试
	vector<int> coll;

	for(int i=0;i<10;i++)
	{
		coll.push_back(i);
	}

	vector<int>::iterator pos=coll.begin();

	copy(coll.begin(),coll.end(),ostream_iterator<int>(cout," "));
	cout<<endl;

	advance(pos,3);//相当于 pos+=n;  而pos+=0;为第一个元素

	cout<<*pos<<endl;

	//deque测试
	deque<int> coll1;

	for(int i=0;i<10;i++)
	{
		coll1.push_front(i);
	}

	deque<int>::iterator pos1=coll1.begin();

	copy(coll1.begin(),coll1.end(),ostream_iterator<int>(cout," "));
	cout<<endl;

	advance(pos1,3);

	cout<<*pos1<<endl;//相当于 pos1+=n;  而pos1+=0;为第一个元素

	//list测试
	list<int> coll2;

	for(int i=1;i<20;i+=2)
	{
		coll2.push_back(i);
	}

	list<int>::iterator pos2=coll2.begin();

	copy(coll2.begin(),coll2.end(),ostream_iterator<int>(cout," "));
	cout<<endl;

	advance(pos2,4);

	cout<<*pos2<<endl;//相当于 pos1+=n;  而pos1+=0;为第一个元素

	set<int> coll3;

	for(int i=1;i<=20;i+=2)
	{
		coll3.insert(i);
	}

	//set测试
	set<int>::iterator pos3=coll3.begin();

	copy(coll3.begin(),coll3.end(),ostream_iterator<int>(cout," "));
	cout<<endl;

	advance(pos3,5);

	cout<<*pos3<<endl;//相当于 pos1+=n;  而pos1+=0;为第一个元素

	//map测试
	map<string,float> coll4;

    coll4["BASF"]=369.50;
	coll4["VW"]=413.50;
	coll4["Daimler"]=819.00;
	coll4["BMW"]=834.00;
	coll4["Siemens"]=842.20;

	map<string,float>::iterator pos4;

	for(pos4=coll4.begin();pos4!=coll4.end();++pos4)
	{
		cout<<"stock: "<<pos4->first<<"\t"
			<<"price: "<<pos4->second<<endl;
	}
	cout<<endl;

	map<string,float>::iterator pos5=coll4.begin();

	advance(pos5,4);

	cout<<pos5->first<<"\t"<<pos5->second<<endl;

	system("pause");
	return 0;
}


你可能感兴趣的:(C++,算法,advance)