c++

c++对象数组怎么排序

小亿
99
2023-12-26 18:12:00
栏目: 编程语言

在C++中,可以使用标准库函数std::sort来对对象数组进行排序。但是在使用std::sort之前,需要定义比较函数或者重载对象的运算符,以便指定对象的排序规则。

以下是一个示例,展示了如何对存储Student对象的数组按照学生年龄进行排序。

#include <algorithm>
#include <iostream>
#include <vector>

class Student {
public:
    std::string name;
    int age;

    Student(std::string name, int age) : name(name), age(age){}

    // 重载运算符<,用于指定排序规则
    bool operator<(const Student& other) const {
        return age < other.age;
    }
};

int main() {
    std::vector<Student> students;
    students.push_back(Student("Alice", 20));
    students.push_back(Student("Bob", 19));
    students.push_back(Student("Charlie", 22));

    // 使用std::sort对students数组进行排序
    std::sort(students.begin(), students.end());

    // 打印排序后的结果
    for (const auto& student : students) {
        std::cout << "Name: " << student.name << ", Age: " << student.age << std::endl;
    }

    return 0;
}

以上代码中,我们定义了一个Student类,其中包含nameage两个成员变量。为了实现对象数组的排序,我们重载了<运算符,指定了按照学生年龄进行比较的规则。

main函数中,我们将Student对象存储在std::vector中,并使用std::sort对数组进行排序。最后,我们遍历排序后的数组并打印结果。输出结果将会按照学生的年龄从小到大进行排序。

0
看了该问题的人还看了