dmndxld

码不停题

c++stack类的用法

官方解释:

LIFO stack

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

stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.

The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:

  • empty
  • size
  • back
  • push_back
  • pop_back


The standard container classes vectordeque and list fulfill these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container deque is used.

 

常用成员函数:

 emplace代码实现:

// 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;
}

结果:

mystack contains:
Second sentence
First sentence

swap代码实现:

 1 // stack::swap
 2 #include <iostream>       // std::cout
 3 #include <stack>          // std::stack
 4 
 5 int main ()
 6 {
 7   std::stack<int> foo,bar;
 8   foo.push (10); foo.push(20); foo.push(30);
 9   bar.push (111); bar.push(222);
10 
11   foo.swap(bar);
12 
13   std::cout << "size of foo: " << foo.size() << '\n';
14   std::cout << "size of bar: " << bar.size() << '\n';
15 
16   return 0;
17 }

结果:

size of foo: 2
size of bar: 3

 

一些思考:emplace跟插入有什么区别呢?

当调用push或insert成员函数时,我们将元素类型的对象传递给它们,这些对象被拷贝到容器中。而当我们调用一个emplace成员函数时,则是将参数传递给元素类型的构造函数。emplace成员使用这些参数在容器管理的内存空间中直接构造元素。

emplace函数的参数根据元素类型而变化,参数必须与元素类型的构造函数相匹配。emplace函数在容器中直接构造元素。传递给emplace函数的参数必须与元素类型的构造函数相匹配。

参考:https://blog.csdn.net/fengbingchun/article/details/78670376

posted on 2019-04-15 21:02  imyourterminal  阅读(7370)  评论(0编辑  收藏  举报

导航