C++ STL 中的 stack emplace()


在本文中,我們將討論 C++ STL 中 stack::emplace() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 Stack?

棧是一種後進先出 (LIFO) 的資料結構,我們在棧的頂部進行插入和刪除操作,最後一個插入的元素位於頂部。就像一堆盤子一樣,如果我們想在棧中新增一個新的盤子,我們把它放在頂部;如果我們想從棧中移除一個盤子,我們也從頂部移除。

什麼是 stack::emplace()?

stack::emplace() 函式是 C++ STL 中的內建函式,它在 `` 標頭檔案中定義。emplace() 用於在與該函式關聯的棧容器中構造和插入一個元素。

當我們執行此函式時,它會在棧的頂部插入一個新元素,並將新插入的元素設為頂部元素。此函式呼叫 emplace_back 函式,在頂部插入新元素。

語法

stack_name.emplace(Args& args);

引數

此函式接受以下引數:

  • **args** - 這些是我們想要放置的引數。

返回值

此函式不返回任何值。

**輸入**

std::stack<int> stack1;
stack1.emplace(1);
stack1.emplace(2);
stack1.emplace(3);

**輸出**

3 2 1

示例

線上演示

#include <iostream>
#include <stack>
using namespace std;
int main(){
   stack<int> stck;
   stck.emplace(10);
   stck.emplace(20);
   stck.emplace(30);
   stck.emplace(40);
   stck.emplace(50);
   stck.emplace(60);
   cout << "Elements in stack are: ";
   while (!stck.empty()){
      cout<<stck.top() << " ";
      stck.pop();
   }
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Elements in stack are: 60 50 40 30 20 10

示例

線上演示

#include <iostream>
#include <stack>
using namespace std;
int main(){
   stack<int> stck;
   int total = 0;
   stck.emplace(10);
   stck.emplace(20);
   stck.emplace(30);
   stck.emplace(40);
   stck.emplace(50);
   stck.emplace(60);
   cout << "Elements in stack are: ";
   while (!stck.empty()){
      cout<<stck.top() << " ";
      stck.pop();
      total++;
   }
   cout<<"\nTotal number of elements in stack are: "<<total;
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Elements in stack are: 60 50 40 30 20 10
Total number of elements in stack are: 6

更新於:2020-04-22

489 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.