📜  C++ STL-stack.emplace()函数

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

C++ stack.emplace()函数

C++ STL stack.emplace()函数在当前顶部元素上方的堆栈顶部添加一个新元素。现在,我们有了一个已有元素的堆栈,我们希望在堆栈中插入或压入一个新元素,为此我们使用了此函数。

句法

template  void emplace (Args&&... args);

参量

args:参数转发用于构造新元素的参数。也就是说,由args指定的元素将插入到当前顶部元素上方的堆栈中。现在,新插入的元素成为顶部元素,并且所有推入和弹出操作都在其上执行。

返回值

该函数仅用于添加新元素,并且不返回任何值。因此,该函数的返回类型为void。

例子1

//该程序通过在堆栈顶部添加两个简单的字符串并进行打印来说明emplace函数的用法。

#include
#include
#include
int main()
{
    std: : stack newstack;
    newstack.emplace (?I am the first line?);
    newstack.emplace (?I am the second one?);
    std: :cout << ?Contents of newstack: \n?;
    while (!newstack.empty () )
    {
        std: :cout << newstack.top () << ?\n?;
        newstack.pop ();
    }
    return 0;
}

输出:

Contents of newstack:
I am the second one
I am the first line

例子2

//该程序通过将11的表格插入到,然后分别进行打印来说明emplace函数的用法。

#include
#include
#include
int main()
{
    std: : stack newstack;
    newstack.emplace (?11?);
    newstack.emplace (?22?);
    newstack.emplace (?33?);
    newstack.emplace (?44?);
    newstack.emplace (?55?);
    newstack.emplace (?66?);
    newstack.emplace (?77?);
    newstack.emplace (?88?);
    newstack.emplace (?99?);
    newstack.emplace (?121?);
    std: :cout << ?Contents of newstack: \n?;
     std: :cout <

输出:

Contents of newstack: 
Table of 11121
99
88
77
66
55
44
33
22
11

例子3

//该程序通过在堆栈顶部添加两个简单的字符串并进行打印来说明emplace函数的用法。

#include
#include
#include
int main()
{
    std::stack newstack;
    newstack.emplace ("We are here to see the application use of emplace function in stacks");
    newstack.emplace ("The function adds new elements are the top of the stack");
    while (!newstack.empty () )
    {
        std::cout << newstack.top () << "\n";
        newstack.pop ();
    }
    return 0;
}

输出:

The function adds new elements are the top of the stack         
We are here to see the application use of emplace function in stacks 

复杂度

对emplace_back进行了一次调用。该函数用于插入新元素,这是通过进行一次调用来完成的。

数据竞争

堆栈中存在的所有元素均被修改。由于该元素被添加到顶部,因此所有其他元素的相应位置也发生了变化。

异常安全

提供与在基础容器对象上执行的操作等效的保证。