C++标准库之stack(各函数及其使用全)

原创作品,转载请注明出处:http://www.cnblogs.com/shrimp-can/p/5283207.html

栈是后入先出的。成员函数有:

1.栈的声明

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() << ' '; std::cout << "size of second: " << second.size() << ' '; std::cout << "size of third: " << third.size() << ' '; std::cout << "size of fourth: " << fourth.size() << ' ';
结果为:0 3 0 2

2.bool empty() const

判断栈是否为空

stack<int> c; c.empty()

3.size_type size() const

返回栈中元素数量

c.size();

4.value_type& top();

   const value_type &top() const;

返回栈顶元素

c.top();

5.void push(const value_type& val)

在栈顶插入一个元素

c.push(value);

6.void emplace(args&& args);

在栈顶增加一个元素

c.emplace(value)

7.void pop()

出栈,即删除栈顶元素

c.pop();

8.void swap (stack& x);

交换两个栈中的内容

c.swap(d);

9.与vector一样,重载了运算符:==   !=   <   <=   >   >=

参考:http://www.cplusplus.com/reference/stack/stack/

 
原文地址:https://www.cnblogs.com/shrimp-can/p/5283207.html