STL初歩のvector用法小記

2066 ワード

STLはc++標準テンプレートライブラリを指し、多くの一般的なアルゴリズムとコンテナが含まれており、vectorはその1つです.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<}(2).下付きループ:vectora;int b=0;for(;b!=a.size;b+){cout<} 5.読み取りサイズ:a.size()6.vectorサイズの変更:a.resize()木塊問題UVA 101の紫書解題コードが添付されており、このコードはvectorを用いて木塊問題を解決する:nを入力し、0 n-1の番号の木塊を得て、それぞれ0 n-1の番号の位置に並べてある。これらの木の塊を操作し、操作は4種類に分けられる。
1、move a onto b:木の塊a、bの上の木の塊をそれぞれの元の位置に戻し、aをbの上に置く.
2、move a over b:a上の木の塊をそれぞれの元の位置に戻し、bを含む山にaを送る.
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;
 	
 }