自己寫了一個小程式,使用vector的好處是他可以不用預設大小
你要在後面塞幾個數字都可以XD~
有人說vector 類似陣列,其實他只是看起來很像陣列
我倒覺得他比較像 linklist
以下是我的sample code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using std::vector;
void pop (vector<int> & );
void push (vector<int> & , int);
void outputVector (vector <int> &);
int main()
{
vector < int > Stack;
int input_num ;
int check;
while ( check !=3 )
{
cout << endl;
cout << "PLEASE ENTER A NUMBER TO STACK" << endl;
cout << "-----------------------------" << endl;
cout << "(1) PUCH" << endl;
cout << "(2) POP" << endl;
cout << "(3) QUIT" << endl;
cout << "-----------------------------" << endl;
cout << endl;
cin >> check;
switch (check)
{
case 1:
cout << "PUSH a integer :";
cin >> input_num;
push ( Stack , input_num);
break;
case 2:
cout << "POP" << endl;
pop (Stack);
break;
case 3:
outputVector (Stack);
break;
}
}
system("PAUSE");
return 0;
}
////////////////////////////////////////////////////////////
void push ( vector<int> &array , int input_num)
{
cout << "push:" << input_num << endl;
if ( input_num >= 0)
{
array.push_back( input_num );
outputVector (array);
}
}
//////////////////////////////////////////////////////////
void pop (vector<int> &array)
{
cout << "pop" ;
array.pop_back();
outputVector (array);
}
/////////////////////////////////////////////////////////
void outputVector (vector<int> &array)
{
cout << "Stack is : " ;
for (int i = 0 ; i < array.size() ;i++ )
{
cout<< array[i] << " ";
}
cout << endl;
}
這是執行結果
選1 : push elementary
選2 : pop
選3 : quit

沒有留言:
張貼留言