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

1949idc 2年前 (2024-09-19) 阅读数 328 #编程语言

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

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

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业