1. 程式人生 > >c++ STL 之 stack

c++ STL 之 stack


 

#define VNAME(value) {cout<<(#value)<<":"<<endl;}

void print_stack(stack<int> v){
	while (!v.empty())
	{
		cout<<v.top()<<" ";
		v.pop();
	}
	cout<<endl;
}


/**
template <class T, class Container = deque<T> > class stack;
**/
void test_stack(){
	//設定容器,預設deque
	std::deque<int> mydeque (3,100);          // deque with 3 elements
	std::vector<int> myvector (2,200);        // vector with 2 elements
	std::stack<int> first;                    // empty stack
	std::stack<int> second (mydeque);         // stack initialized to copy of deque
	std::stack<int,std::vector<int> > third;  // empty stack using vector
	std::stack<int,std::vector<int> > fourth (myvector);

	std::cout << "size of first: " << first.size() << '\n';
	std::cout << "size of second: " << second.size() << '\n';
	std::cout << "size of third: " << third.size() << '\n';
	std::cout << "size of fourth: " << fourth.size() << '\n';

	if (first.empty())
	{
		cout<<"stack first is empty."<<endl;
	}

	first.push(3);
	first.push(4);
	//first.pop();
	VNAME(first);
	print_stack(first);

	first.swap(second);		//交換兩個棧的資料
	VNAME(first);
	print_stack(first);

	cout<<" top element is "<<first.top()<<endl;

	//關係操作符==, != ,< ,> ,<=,>=

	cout<<endl<<endl;
}