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

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


งานนี้เป็นการแสดงฟังก์ชันการทำงานของ list::unique() ใน C++ STL

List ใน STL คืออะไร

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

unique() คืออะไร

ฟังก์ชัน list::unique() ใช้ลบองค์ประกอบซ้ำทั้งหมดใน list

ไวยากรณ์

list_name.unique(binary_predicate name)

ไวยากรณ์สำหรับ binary predicate

bool name(data_type a, data_type b)

พารามิเตอร์

ฟังก์ชันนี้รับพารามิเตอร์เดียวซึ่งเป็น binary predicate ที่คืนค่า true หากองค์ประกอบควรถือว่าเท่ากัน

ตัวอย่าง

อินพุต List - 2 2 6 7 9 9 9 10 5 5

เอาต์พุต New List - 2 5 6 7 9 10

อินพุต List - 3.14 5.56 7.62 9.00 0.45 7.62 9.00 7.62 0.45 3.00

เอาต์พุต New List - 0.45 3.00 3.14 5.56 7.62 9.00

แนวทางการทำงาน

  • สร้างฟังก์ชัน binary predicate ก่อน
  • เริ่มต้น list
  • กำหนดฟังก์ชัน unique()
  • พิมพ์ list หลังการดำเนินการ unique

ด้วยแนวทางด้านบน เราสามารถลบองค์ประกอบซ้ำจาก list ได้

ตัวอย่าง

// C++ code to demonstrate the working of list unique() function in STL
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;

// function for binary predicate
bool cmp(int a, int b) {
    return (abs(a) == abs(b));
}

int main() {
    list<int> lst = { 13, 14, 13, 19, 20, 19, 15, 19, 20, 15, 15 };
    // print the list
    cout << "Elements in List: ";
    for(auto x = lst.begin(); x != lst.end(); ++x)
        cout << *x << " ";
    // declaring unique() function
    lst.unique(cmp);
    // printing new list after unique operation
    cout << "\nList after unique operation: ";
    for(auto x = lst.begin(); x != lst.end(); ++x)
        cout << *x << " ";
    return 0;
}

เอาต์พุต

Elements in List: 13 14 13 19 20 19 15 19 20 15 15
List after unique operation: 13 14 19 20 15

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

// C++ code to demonstrate the working of list unique() function in STL
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;

// function for binary predicate
bool cmp(float a, float b) {
    return (abs(a) == abs(b));
}

int main() {
    list<float> lst = { 3.14, 5.56, 7.62, 9.00, 0.45, 7.62, 9.00, 7.62, 0.45, 3.00 };
    // print the list
    cout << "Elements in List: ";
    for(auto x = lst.begin(); x != lst.end(); ++x)
        cout << *x << " ";
    // declaring unique() function
    lst.unique(cmp);
    // printing new list after unique operation
    cout << "\nList after unique operation: ";
    for(auto x = lst.begin(); x != lst.end(); ++x)
        cout << *x << " ";
    return 0;
}

เอาต์พุต

Elements in List: 3.14 5.56 7.62 9.00 0.45 7.62 9.00 7.62 0.45 3.00
List after unique operation: 0.45 3.00 3.14 5.56 7.62 9.00