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

Merge Operations ใน C++ STL: merge, includes, set_union, set_intersection, set_difference, inplace_merge


ในบทเรียนนี้ เราจะอธิบาย Merge Operations ต่างๆ ใน C++ STL (<algorithm>)

1. merge()

รวม 2 Container ที่เรียงแล้ว ให้ได้ Container ใหม่ที่เรียงแล้ว

2. includes()

ตรวจสอบว่า Container แรกมี Element ครอบคลุม Container ที่สองหมดหรือไม่

3. set_union()

Union ของ 2 เซต (Element ทั้งหมด ไม่ซ้ำ)

4. set_intersection()

Intersection ของ 2 เซต (Element ที่อยู่ในทั้งคู่)

5. set_difference()

Element ที่อยู่ในเซตแรก แต่ไม่อยู่ในเซตที่สอง

6. inplace_merge()

Merge 2 ส่วนที่เรียงแล้วใน Container เดียวกัน ให้เรียงทั้งหมด

ตัวอย่าง

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    vector<int> v1 = {1, 3, 4, 5, 20, 30};
    vector<int> v2 = {1, 5, 6, 7, 25, 30};
    
    // merge
    vector<int> v3(v1.size() + v2.size());
    merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
    
    cout << "Merged: ";
    for (int x : v3) cout << x << " ";
    cout << endl;
    
    // includes
    vector<int> v4 = {1, 3, 4, 5, 6, 20, 25, 30};
    cout << (includes(v4.begin(), v4.end(), v1.begin(), v1.end()) 
         ? "v4 includes v1" : "v4 doesn't include v1") << endl;
    
    return 0;
}

ผลลัพธ์

Merged: 1 1 3 4 5 5 6 7 20 25 30 30
v4 includes v1

ตารางสรุป

Functionวัตถุประสงค์Input ต้องเรียง?
mergeรวม 2 range เรียงYes
includesเช็ค subsetYes
set_unionยูเนียน (ไม่ซ้ำ)Yes
set_intersectionอินเตอร์เซกชันYes
set_differenceความต่าง A-BYes
inplace_mergemerge ใน container เดียวYes (2 ส่วนติดกัน)