📜  C++ STL-stack

📅  最后修改于: 2020-10-19 00:54:08             🧑  作者: Mango

C++堆栈

在计算机科学领域,我们致力于各种程序。他们每个人都有自己的域和实用程序。根据程序创建的目的和环境,我们有大量数据结构可供选择。其中之一是“堆栈”。在讨论这种数据类型之前,让我们看一下它的语法。

句法

template > class stack;

此数据结构适用于LIFO技术,其中LIFO代表后进先出。首先插入的元素将在末尾提取,依此类推。有一个称为“顶部”的元素,它是位于最高位置的元素。所有插入和删除操作都是在堆栈的顶部元素本身进行的。

应用区域中的堆栈暗示为容器适配器。

容器应支持以下操作列表:

  • 空的
  • 尺寸
  • 背部
  • 推回
  • pop_back

模板参数

T:该参数指定容器适配器将保留的元素的类型。

容器:该参数指定容器的内部对象,其中包含堆栈的元素。

会员类型

下面给出了堆栈成员类型的列表,并对其进行了简短描述。

Member Types Description
value_type Element type is specified.
container_type Underlying container type is specified.
size_type It specifies the size range of the elements.

功能

借助功能,可以在编程领域中使用对象或变量。堆栈提供了大量可以在程序中使用或嵌入的功能。相同的列表如下:

Function Description
(constructor) The function is used for the construction of a stack container.
empty The function is used to test for the emptiness of a stack. If the stack is empty the function returns true else false.
size The function returns the size of the stack container, which is a measure of the number of elements stored in the stack.
top The function is used to access the top element of the stack. The element plays a very important role as all the insertion and deletion operations are performed at the top element.
push The function is used for the insertion of a new element at the top of the stack.
pop The function is used for the deletion of element, the element in the stack is deleted from the top.
emplace The function is used for insertion of new elements in the stack above the current top element.
swap The function is used for interchanging the contents of two containers in reference.
relational operators The non member function specifies the relational operators that are needed for the stacks.
uses allocator As the name suggests the non member function uses the allocator for the stacks.

示例:一个简单的程序,显示基本堆栈功能的用法。

#include 
#include 
using namespace std;
void newstack(stack  ss)
{
    stack  sg = ss;
    while (!sg.empty())
    {
        cout << '\t' << sg.top();
        sg.pop();
    }
    cout << '\n';
}
int main ()
{
    stack  newst;
    newst.push(55);
    newst.push(44);
    newst.push(33);
    newst.push(22);
    newst.push(11);

    cout << "The stack newst is : ";
    newstack(newst);
    cout << "\n newst.size() : " << newst.size();
    cout << "\n newst.top() : " << newst.top();
    cout << "\n newst.pop() : ";
    newst.pop();
    newstack(newst); 
    return 0;
}

输出:

The stack newst is :     11    22    33    44    55

 newst.size() : 5
 newst.top() : 11
 newst.pop() :     22    33    44    55