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

ฟังก์ชัน emplace() ของ list ใน C++ STL

บทนำ

งานนี้แสดงการทำงานของ list::emplace() ใน C++

list::emplace() เป็นส่วนหนึ่งของ C++ STL ใช้แทรกค่าเข้าไปในลิสต์ที่ตำแหน่งที่ผู้ใช้ระบุ

ต้อง include <list>

Syntax

List_Name.emplace(position, element)

Parameters

  • Position - ตำแหน่งที่จะวางอิลิเมนต์ใหม่
  • Value - อิลิเมนต์ที่จะแทรก

Return Value

คืนค่า Iterator ชี้ไปที่อิลิเมนต์ที่เพิ่งแทรก

ตัวอย่าง

Input: list<int> L = { 1, 2, 3 }
Output: 6 1 2 3

คำอธิบาย - สร้าง L = {1,2,3} สร้าง iterator itr ใช้ emplace() วาง 6 ที่ตำแหน่งเริ่มต้น (L.begin()) ได้ 6 1 2 3

แนวทางในโปรแกรม

  • สร้าง list Lt ประเภท int กำหนดค่า
  • สร้าง iterator itr เรียก emplace() รับค่าคืน
  • อาร์กิวเมนต์: Lt.end() (ตำแหน่งท้าย) และค่า 7

อัลกอริทึม

Start
Step 1 → In main()
    Initialize list<int> Lt = {}
    Initialize auto itr = Lt.emplace(Lt.end(), 7)
    Loop for itr = Lt.begin() to itr != Lt.end() itr++
    Print *itr
Stop

ตัวอย่างโค้ด

#include <iostream>
#include <list>
using namespace std;

int main() {
    list<int> Lt = { 3, 4, 5 };
    auto itr = Lt.emplace(Lt.begin(), 7);
    Lt.emplace(itr, 6);
    cout << "The List is: ";
    for (itr = Lt.begin(); itr != Lt.end(); itr++)
        cout << *itr << " ";
    return 0;
}

ผลลัพธ์

The List is: 6 7 3 4 5

คำอธิบาย

emplace(Lt.begin(), 7) แทรก 7 หน้าสุด → {7, 3, 4, 5} คืน iterator ชี้ 7

emplace(itr, 6) แทรก 6 ก่อน iterator (ซึ่งชี้ 7) → {6, 7, 3, 4, 5}

emplace() แตกต่างจาก insert() ที่สร้างออบเจ็กต์ในที่โดยตรง (In-place construction) ประหยัดการ Copy/Move