C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ Stack emplace()

C++ Stack emplace()函数

C++堆栈emplace()函数在当前顶部元素上方的堆栈顶部添加一个新元素。现在,我们有了一个已经存在元素的堆栈,并且我们希望在堆栈中插入或推送一个新元素,为此,我们使用了此功能。

语法

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

参数

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

返回值

该函数仅用于添加元素,不返回任何值。因此,该函数的返回类型为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进行了一次调用。该函数用于插入新元素,只需执行一次调用即可完成。

数据竞争

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

异常安全性

与执行的操作等效的保证在基础容器对象上提供了。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4