C++ STL 中的 push_front() 函式


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

什麼是 STL 中的列表

列表是一種資料結構,它允許在序列中的任何位置進行常數時間插入和刪除。列表以雙向連結串列的形式實現。列表允許非連續記憶體分配。與陣列、向量和雙端佇列相比,列表在容器的任何位置執行元素的插入、提取和移動方面表現更好。在列表中,對元素的直接訪問速度很慢,並且列表類似於 forward_list,但 forward_list 物件是單向連結串列,它們只能向前迭代。

什麼是 push_front()

push_front() 是 C++ STL 中的一個內建函式,它在標頭檔案中宣告。push_front() 用於將元素推入(插入)到列表容器的開頭。如果容器為空,則將其推入第一個位置,並且該元素成為第一個元素;如果容器事先包含元素,則該函式將其傳遞的元素推入前面,而先前位於第一個位置的元素將成為第二個元素。此函式將容器的大小增加 1。

語法

void push_front (const value_type& element1);
void push_front (value_type&& element1);
This function accepts only 1 element which is to be pushed/inserted.

返回值

此函式不返回任何內容。

示例

#include <bits/stdc++.h>
using namespace std;
int main(){
   //create a list
   list myList;
   //insert elements
   myList.push_back(1);
   myList.push_back(2);
   myList.push_back(3);
   myList.push_back(4);
   //List before applying push_front()
   cout<<"List : ";
   for (auto i = myList.begin(); i!= myList.end(); i++)
      cout << *i << " ";
   //calling push_front()
   myList.push_front(0);
   cout<<"\nList after calling push_front() : ";
   for (auto i = myList.begin(); i!= myList.end(); i++)
      cout << *i << " ";
   return 0;
}

輸出

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

List : 1 2 3 4
List after calling push_front(): 4 3 2 1

示例

 線上演示

#include <iostream>
#include <list>
int main (){
   //adding two integer values with the value 30
   std::list<int> myList (2,30);
   myList.push_front (20);
   myList.push_front (10);
   std::cout<<"elements in my list are : ";
   for (std::list<int>::iterator i = myList.begin(); i!= myList.end(); ++i)
      std::cout << ' ' << *i;
   std::cout << '\n';
   return 0;
}

輸出

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

Elements in my list are : 10 20 30 30

更新於: 2020年2月26日

378 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.