Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน list::push_front() ใน C++ STL


ในบทความนี้เราจะอภิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน push_front() ใน C++

List ใน STL คืออะไร

List เป็นโครงสร้างข้อมูลที่อนุญาตให้แทรกและลบได้ในเวลาคงที่ที่ตำแหน่งใดก็ตามในลำดับ List ถูกนำไปใช้เป็น doubly linked lists List อนุญาตการจัดสรรหน่วยความจำแบบไม่ต่อเนื่อง List ทำงานการแทรก ดึง และย้ายองค์ประกอบได้ดีกว่า array, vector และ deque ใน List การเข้าถึงองค์ประกอบโดยตรงช้า และ list คล้ายกับ forward_list แต่วัตถุ forward_list เป็น singly linked lists และสามารถวนรอบได้เฉพาะไปข้างหน้า

push_front() คืออะไร

push_front() เป็นฟังก์ชันในตัวใน C++ STL ซึ่งประกาศในไฟล์หัวเรื่อง push_front() ใช้ push (แทรก) องค์ประกอบที่จุดเริ่มต้นของคอนเทนเนอร์ list ถ้าคอนเทนเนอร์ว่าง มันจะแทรกองค์ประกอบที่ตำแหน่งแรกและองค์ประกอบจะกลายเป็นองค์ประกอบแรก และถ้าคอนเทนเนอร์มีองค์ประกอบอยู่แล้ว ฟังก์ชันจะแทรกองค์ประกอบที่ส่งมาไปหน้า และองค์ประกอบเดิมที่อยู่ตำแหน่งแรกจะกลายเป็นองค์ประกอบที่สอง ฟังก์ชันนี้เพิ่มขนาดของคอนเทนเนอร์ขึ้น 1

ไวยากรณ์

void push_front(const value_type& element1);
void push_front(value_type&& element1);
ฟังก์ชันนี้รับเพียง 1 องค์ประกอบที่จะ push/แทรก

ค่าที่คืน

ฟังก์ชันนี้ไม่คืนค่าอะไร

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

int main() {
    // create a list
    list<int> 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(): 0 1 2 3 4

ตัวอย่างที่ 2

#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