STL初步之 vector用法小记

STL指c++标准模板库,其中包含很多常用算法和容器,vector就是其中之一。
vector是一个模板类,能够像容器一样存放各种类型的对象,vector就像是一种动态数组,它拥有数组的所有功能并且能够动态增长。
简单用法:
1.定义一个vector: vectora;
2.插入数值:a.push_back(a);//在末尾插入a
a.insert(a.begin()+i,j);//在第i+1个元素前面插入j
3.删除: a.pop_back();//删除vector最后的元素
a.erase(a.begin()+n);//删除第n+1个元素
a.erase(a.begin()+n,a.end()+m);//删除整个区间[n,m-1]
a.clear();//清空vector元素
4(1).使用迭代器遍历vector元素 :vector::iterator iter;
for(iter=a.begin();iter!=a.end();iter++)
{
cout<<*iter;
}
(2).使用下标遍历:
vectora;
int b=0;
for(;b!=a.size;b++)
{
cout< }
5.读取大小:a.size();
6.改变vector大小:a.resize();
另附木块问题UVA101的紫书解题代码,该代码使用了vector解决
木块问题:输入n,得到编号为0n-1的木块,分别摆放在顺序排列编号为0n-1的位置。现对这些木块进行操作,操作分为四种。

1、move a onto b:把木块a、b上的木块放回各自的原位,再把a放到b上;

2、move a over b:把a上的木块放回各自的原位,再把a发到含b的堆上;

3、pile a onto b:把b上的木块放回各自的原位,再把a连同a上的木块移到b上;

4、pile a over b:把a连同a上木块移到含b的堆上。

当输入quit时,结束操作并输出0~n-1的位置上的木块情况

Sample Input
10
move 9 onto 1
move 8 over 1
move 7 over 1
move 6 over 1
pile 8 over 6
pile 8 over 5
move 2 over 1
move 4 over 9
quit
Sample Output
0: 0
1: 1 9 2 4
2:
3: 3
4:
5: 5 8 7 6
6:
7:
8:

9:

#include
#include
#include
 
using namespace std;
 
const int maxn = 30;
int n;
vector pile[maxn];
 
void find_block(int a,int &p,int &h)     //找到木块a所在的pile和height 
{
	for(p = 0;p>n;
 	string s1,s2;
 	for(int i=0;i>s1>>a>>s2>>b)
 	{
 		int pa,pb,ha,hb;
 		find_block(a,pa,ha);
 		find_block(b,pb,hb);
 		if(pa == pb)
 			continue;
 		if(s2 == "onto")
 			clear_above(pb,hb);
 		if(s2 == "move")
 			clear_above(pa,ha);
 		pile_onto(pa,ha,pb);
	 }
 	show();
 	return 0;
 	
 }

你可能感兴趣的:(水题)