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

set::emplace_hint() ใน C++ STL


ในบทความนี้เราจะอธิบายฟังก์ชัน set::emplace_hint() ใน C++ STL รวมถึงไวยากรณ์ การทำงาน และค่าที่ส่งคืน

Set ใน C++ STL คืออะไร?

Set ใน C++ STL เป็นคอนเทนเนอร์ที่เก็บ องค์ประกอบที่ไม่ซ้ำกัน (unique) ในลำดับที่จัดเรียงแล้ว ค่าขององค์ประกอบระบุตัวตนของมันเอง เมื่อเพิ่มค่าใน set แล้วไม่สามารถแก้ไขได้ แต่ยังสามารถลบหรือเพิ่มค่าใหม่ได้ Set ถูกนำไปใช้งานเป็น binary search tree

set::emplace_hint() คืออะไร?

emplace_hint() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <set> ฟังก์ชันนี้ แทรกองค์ประกอบใหม่ใน set container พร้อมกับ hint position ใน emplace_hint() เราส่งค่าพร้อมกับตำแหน่ง hint ฟังก์ชันจะค้นหาตำแหน่งที่เหมาะสมตั้งแต่ hint position และแทรกที่นั่น (ถ้ายังไม่มีค่าเท่ากันใน set)

ไวยากรณ์ (Syntax)

Set1.emplace_hint(iterator position, const type_t& value);

พารามิเตอร์ (Parameters)

รับพารามิเตอร์ 2 ค่า:

  • Position – hint position เริ่มค้นหาตำแหน่งที่จะแทรกจากที่นี่ (ทำให้ทำงานเร็วขึ้น แต่ไม่บังคับตำแหน่งแน่นอน)
  • Value – ค่าจริงที่ต้องการ emplace

ค่าที่ส่งคืน (Return Value)

ส่งคืน iterator ไปยองค์ประกอบที่แทรกใหม่ หากแทรกสำเร็จ

ตัวอย่างการใช้งาน

Input: set<int> mySet;
mySet.emplace_hint(mySet.begin(), 0);
mySet.emplace_hint(i, 1);
mySet.emplace_hint(i, 2);
mySet.emplace_hint(i, 1); // ซ้ำ จะไม่แทรก
Output: Elements are : 0 1 2

ตัวอย่างโค้ดเต็ม 1

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

int main() {
    set<int> mySet;
    auto i = mySet.emplace_hint(mySet.begin(), 0);
    i = mySet.emplace_hint(i, 1);
    mySet.emplace_hint(i, 2);
    mySet.emplace_hint(i, 1); // ค่าซ้ำ จะถูกข้าม
    
    cout << "elements are : ";
    for (auto i = mySet.begin(); i != mySet.end(); i++)
        cout << *i << " ";
    return 0;
}

ผลลัพธ์ (Output)

Elements are : 0 1 2

ตัวอย่างโค้ดเต็ม 2 (ใช้ string)

#include <iostream>
#include <set>
#include <string>

int main() {
    std::set<std::string> mySet;
    auto i = mySet.cbegin();
    mySet.emplace_hint(i, "best");
    i = mySet.emplace_hint(mySet.cend(), "point");
    i = mySet.emplace_hint(i, "is the");
    i = mySet.emplace_hint(i, "tutorials");
    
    std::cout << "string is : ";
    for(const std::string& str : mySet)
        std::cout << ' ' << str;
    std::cout << '\n';
    return 0;
}

ผลลัพธ์ (Output)

String is : best is the point tutorials