STL学习笔记——2.stack

来源:互联网 发布:软件开发项目管理 pdf 编辑:程序博客网 时间:2024/05/17 20:33

     之前被学长坑了,非要模拟栈,以至于现在完全看不懂网上用STL写的代码,只有现学了(╯‵□′)╯︵┻━┻。

以下资料主要参考网站http://www.cplusplus.com/reference/stack/stack/

class template

<stack>

std::stack

template <class T, class Container = deque<T> > class stack;

LIFO stack

Stacks are a typeof container adaptor, specifically designed to operate in a LIFO context(last-in first-out), where elements are inserted and extracted only from oneend of the container.

stacks are implemented ascontainers adaptors, which are classes thatuse an encapsulated object of a specific container class as itsunderlyingcontainer, providing a specific set of member functions to access itselements. Elements arepushed/popped from the"back"of the specific container, which is known as thetop of the stack.

The underlying container may be any of the standard container class templatesor some other specifically designed container class. The container shallsupport the following operations:
  • empty
  • size
  • back
  • push_back
  • pop_back


The standard container classes vector,dequeandlist fulfill these requirements. By default, if no container class isspecified for a particularstack class instantiation, the standard containerdeque is used.


Template parameters

T

Type of theelements.
Aliased as member type
stack::value_type.

Container

Type of theinternal underlying container object where the elements are stored.
Its
value_typeshall beT.
Aliased as member type
stack::container_type.

头文件:

#include<strack>(或者直接写#include<bits/stdc++.h>)

声明:

若已声明命名空间(using namespace std),则写作stack<变量类型>变量名(一定要找一个自己喜欢的\(^o^)/~,要不然就找一个有实际意义的٩( ‘ω’ )و get

若未声明命名空间,则写作std::stack<std::变量类型>变量名。

         常用函数

std::stack::pop

void pop();

Remove top element

Removes theelement on top of the stack,effectively reducing itssizeby one.

The element removed is the latest element inserted into the
stack, whose value can be retrieved by calling member stack::top.

This calls the removed element's destructor.

This member function effectively calls the member function
pop_back of the underlying container object.


Parameters

none


Return value

none

std::stack::push

  • C++98
  • C++11
  •  
void push (const value_type& val);
void push (const value_type& val);
void push (value_type&& val);

Insert element

Inserts a newelement at the top of the stack,above its currenttop element.The content of this new element is initialized to a copy ofval.

This member function effectively calls the member function
push_back of theunderlying container object.


Parameters

val

Value to whichthe inserted element is initialized.
Member type
value_type is the type of the elements in the container (defined as an aliasof the first class template parameter,T).



Return value

none

其实,这里的poppush意思和queue那个差距真的不大……

看看代码就知道了:

// stack::push/pop#include <iostream>       // std::cout#include <stack>          // std::stackint main (){  std::stack<int> mystack;  for (int i=0; i<5; ++i) mystack.push(i);  std::cout << "Popping out elements...";  while (!mystack.empty())  {     std::cout << ' ' << mystack.top();     mystack.pop();  }  std::cout << '\n';  return 0;}
Output:

Popping out elements... 4 3 2 1 0

std::stack::size

size_type size() const;

Return size

Returns thenumber of elements in thestack.

This member function effectively calls member
sizeof the underlying container object.


Parameters

none


Return Value

The number of elements in theunderlyingcontainer.

Member type
size_type is an unsigned integral type.

这里的size也与queue那个size差距不大,似乎STL中同名的函数用法和意义都是相近的

直接放代码了:

// stack::size#include <iostream>       // std::cout#include <stack>          // std::stackint main (){  std::stack<int> myints;  std::cout << "0. size: " << myints.size() << '\n';  for (int i=0; i<5; i++) myints.push(i);  std::cout << "1. size: " << myints.size() << '\n';  myints.pop();  std::cout << "2. size: " << myints.size() << '\n';  return 0;}Edit & Run

Output:

0. size: 01. size: 52. size: 4

std::stack::swap

void swap (stack& x) noexcept(/*see below*/);

Swap contents

Exchanges thecontents of the container adaptor (*this) by those ofx.

This member function calls the non-member function
swap (unqualified) to swap theunderlying containers.

The
noexcept specifier matches theswapoperation on theunderlying container.


Parameters

x

Another stack container adaptor of the same type (i.e., instantiated with thesame template parameters, T andContainer). Sizes may differ.



Return value

none

这个也直接放代码了:
// stack::swap#include <iostream>       // std::cout#include <stack>          // std::stackint main (){  std::stack<int> foo,bar;  foo.push (10); foo.push(20); foo.push(30);  bar.push (111); bar.push(222);  foo.swap(bar);  std::cout << "size of foo: " << foo.size() << '\n';  std::cout << "size of bar: " << bar.size() << '\n';  return 0;}

Output:
size of foo: 2size of bar: 3

std::stack::top

  • C++98
  • C++11
  •  
      value_type& top();
const value_type& top() const;
      reference& top();
const_reference& top() const;

Access next element

Returns areference to the top element in thestack.

Since stacks are last-in first-out containers, the
topelement is the last element inserted into the stack.

This member function effectively calls member
backof theunderlying container object.


Parameters

none


Return value

A reference tothe top element in thestack.

  • C++98
  • C++11
  •  

Member type value_type is the type of the elements in the container (defined as an aliasof the first class template parameter,T).

也没什么生单词,蛮好懂的,也直接附上代码:
// stack::top#include <iostream>       // std::cout#include <stack>          // std::stackint main (){  std::stack<int> mystack;  mystack.push(10);  mystack.push(20);  mystack.top() -= 5;  std::cout << "mystack.top() is now " << mystack.top() << '\n';  return 0;}Edit & Run

Output:
mystack.top() is now 15

std::stack::empty

bool empty() const;

Test whether container is empty

Returns whetherthe stack is empty: i.e. whether its size iszero.

This member function effectively calls member
emptyof theunderlying container object.


Parameters

none


Return Value

true if the underlying container'ssize is 0, false otherwise.
// stack::empty#include <iostream>       // std::cout#include <stack>          // std::stackint main (){  std::stack<int> mystack;  int sum (0);  for (int i=1;i<=10;i++) mystack.push(i);  while (!mystack.empty())  {     sum += mystack.top();     mystack.pop();  }  std::cout << "total: " << sum << '\n';  return 0;}

The example initializes the content of the stack to a sequence of numbers (form 1 to 10). It then pops the elements one by one until it is empty and calculates their sum.

Output:
total: 55

std::stack::emplace

template <class... Args> void emplace (Args&&... args);

Construct and insert element

Adds a newelement at the top of the stack,above its currenttop element. This new element is constructed in placepassingargs as the arguments for itsconstructor.

This member function effectively calls the member function
emplace_back of the underlying container,forwardingargs.


Parameters

args

Argumentsforwarded to construct the new element.



Return value

none

// stack::emplace#include <iostream>       // std::cin, std::cout#include <stack>          // std::stack#include <string>         // std::string, std::getline(string)int main (){  std::stack<std::string> mystack;  mystack.emplace ("First sentence");  mystack.emplace ("Second sentence");  std::cout << "mystack contains:\n";  while (!mystack.empty())  {    std::cout << mystack.top() << '\n';    mystack.pop();  }  return 0;}
Output:

mystack contains:Second sentenceFirst sentence




注意:一定要记得写(),曾经因为没有写()被编译器嘲笑了无数次(就像刚刚开始学c++的时候因为没有写“;”的习惯被编译器嘲笑到哭泣)。

原创粉丝点击