C++ Stack emplace() 函数

C++ Stack emplace() 函数

C++ Stack emplace() 函数在当前栈顶元素的上方添加一个新元素。现在,我们有一个已存在元素的栈,我们希望在栈中插入或推送一个新元素,我们使用这个函数来实现。

语法

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

参数

args :该参数用于新元素的构造。即由args指定的元素插入到堆栈的当前顶部元素之上。新插入的元素现在成为顶部元素,所有的push和pop操作都在它上面进行。

返回值

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

示例1

//此程序通过在堆栈顶部添加两个简单的字符串并打印它们来说明emplace函数的使用。

#include<iostream>
#include<stack>
#include<string>
int main()
{
    std: : stack<std: : string> 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<iostream>
#include<stack>
#include<string>
int main()
{
    std: : stack<std: : string> 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 <<?Table of 11?;

    while (!newstack.empty () )
    {
        std: :cout << newstack.top () << ?\n?;
        newstack.pop ();
    }
    return 0;
}

输出:

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

示例3

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

#include<iostream>
#include<stack>
#include<string>
int main()
{
    std::stack<std::string> 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进行一次调用。该函数用于通过一次调用来插入一个新元素。

数据竞争

栈中的所有元素都被修改。由于元素被添加到顶部,因此所有其他元素的位置也会改变。

异常安全

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程