溫馨提示×

如何對C++ struct數(shù)組進(jìn)行排序和查找

c++
小樊
95
2024-09-10 19:28:36
欄目: 編程語言

在 C++ 中,可以使用庫中的sort()函數(shù)對結(jié)構(gòu)體數(shù)組進(jìn)行排序,使用binary_search()` 函數(shù)進(jìn)行查找。這里有一個示例展示了如何實現(xiàn)這兩個操作:

首先,定義一個結(jié)構(gòu)體類型,并包含所需的數(shù)據(jù)成員:

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

struct Student {
    int id;
    string name;
};

接下來,編寫一個比較函數(shù),用于在排序時比較結(jié)構(gòu)體中的特定數(shù)據(jù)成員。在本例中,我們將根據(jù)學(xué)生的 ID 進(jìn)行排序:

bool compareStudents(const Student &a, const Student &b) {
    return a.id < b.id;
}

然后,創(chuàng)建一個結(jié)構(gòu)體數(shù)組,并添加一些數(shù)據(jù):

int main() {
    Student students[] = {
        {3, "Alice"},
        {1, "Bob"},
        {4, "Charlie"},
        {2, "David"}
    };
    
    int n = sizeof(students) / sizeof(Student);

現(xiàn)在,使用 sort() 函數(shù)對結(jié)構(gòu)體數(shù)組進(jìn)行排序:

    sort(students, students + n, compareStudents);

接下來,使用 binary_search() 函數(shù)查找特定元素。為此,請?zhí)峁┮檎业?ID 值:

    int targetId = 2;
    bool found = binary_search(students, students + n, targetId,
                              [](const Student &s, int id) { return s.id < id; });

最后,輸出排序后的數(shù)組以及查找結(jié)果:

    cout << "Sorted array: "<< endl;
    for (int i = 0; i < n; ++i) {
        cout<< students[i].id << ": "<< students[i].name<< endl;
    }

    if (found) {
        cout << "Found student with ID: "<< targetId<< endl;
    } else {
        cout << "Student not found"<< endl;
    }

    return 0;
}

完整代碼如下:

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

struct Student {
    int id;
    string name;
};

bool compareStudents(const Student &a, const Student &b) {
    return a.id < b.id;
}

int main() {
    Student students[] = {
        {3, "Alice"},
        {1, "Bob"},
        {4, "Charlie"},
        {2, "David"}
    };
    
    int n = sizeof(students) / sizeof(Student);

    sort(students, students + n, compareStudents);

    int targetId = 2;
    bool found = binary_search(students, students + n, targetId,
                              [](const Student &s, int id) { return s.id < id; });

    cout << "Sorted array: "<< endl;
    for (int i = 0; i < n; ++i) {
        cout<< students[i].id << ": "<< students[i].name<< endl;
    }

    if (found) {
        cout << "Found student with ID: "<< targetId<< endl;
    } else {
        cout << "Student not found"<< endl;
    }

    return 0;
}

運行此程序,你將看到已排序的學(xué)生數(shù)組以及查找結(jié)果。

0