c++

如何对C++ struct数组进行排序和查找

小樊
85
2024-09-10 19:28:36
栏目: 编程语言

在 C++ 中,可以使用库中的sort()函数对结构体数组进行排序,使用binary_search()` 函数进行查找。这里有一个示例展示了如何实现这两个操作:

首先,定义一个结构体类型,并包含所需的数据成员:

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

struct Student {
    int id;
    string name;
};

接下来,编写一个比较函数,用于在排序时比较结构体中的特定数据成员。在本例中,我们将根据学生的 ID 进行排序:

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() 函数对结构体数组进行排序:

    sort(students, students + n, compareStudents);

接下来,使用 binary_search() 函数查找特定元素。为此,请提供要查找的 ID 值:

    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;
}

完整代码如下:

#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;
}

运行此程序,你将看到已排序的学生数组以及查找结果。

0
看了该问题的人还看了