You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中对Person子类列表按ID排序的实现问题求助

解决方案:按类型/优先级排序list<Person*>

方法1:面向对象式的优先级排序(推荐)

给基类定义一个纯虚函数,让子类返回各自的排序优先级(Student返回1,Employee返回2),排序时直接比较这个优先级数值即可,扩展性极强。

示例代码:

#include <list>
#include <algorithm>

class Person {
public:
    virtual ~Person() = default; // 基类必须加虚析构,避免内存泄漏
    virtual int getSortPriority() const = 0; // 纯虚函数,子类实现
};

class Student : public Person {
public:
    int getSortPriority() const override {
        return 1; // 优先级更高,排在前面
    }
};

class Employee : public Person {
public:
    int getSortPriority() const override {
        return 2; // 优先级更低,排在后面
    }
};

// 排序比较函数
bool sorting_id(const Person* a, const Person* b) {
    return a->getSortPriority() < b->getSortPriority();
}

// 使用示例
int main() {
    std::list<Person*> people;
    people.push_back(new Employee());
    people.push_back(new Student());
    people.push_back(new Employee());
    people.push_back(new Student());

    people.sort(sorting_id); // 调用list的sort方法完成排序

    // 记得最后遍历释放所有对象内存
    for (auto p : people) {
        delete p;
    }
    return 0;
}

以后新增子类(比如Teacher),只需要重写getSortPriority()返回对应数值,完全不用修改排序逻辑。

方法2:直接通过类型判断排序

如果不想改动基类代码,可以用typeid识别对象实际类型,直接按类型排序。注意必须给基类加虚析构,否则typeid无法正确识别子类类型。

示例代码:

#include <list>
#include <algorithm>
#include <typeinfo>

class Person {
public:
    virtual ~Person() = default; // 虚析构是typeid正确识别类型的前提
};

class Student : public Person {};
class Employee : public Person {};

// 排序比较函数
bool sorting_by_type(const Person* a, const Person* b) {
    // Student排Employee前面
    if (typeid(*a) == typeid(Student) && typeid(*b) == typeid(Employee)) {
        return true;
    }
    // Employee不能排Student前面
    if (typeid(*a) == typeid(Employee) && typeid(*b) == typeid(Student)) {
        return false;
    }
    // 同类型保持原顺序
    return false;
}

// 使用示例
int main() {
    std::list<Person*> people;
    people.push_back(new Employee());
    people.push_back(new Student());
    people.push_back(new Employee());
    people.push_back(new Student());

    people.sort(sorting_by_type);

    // 释放内存
    for (auto p : people) {
        delete p;
    }
    return 0;
}

这种方式扩展性差,新增子类时必须修改排序函数的判断逻辑,适合临时快速解决问题。

原报错原因说明

你用id.compare()报错,是因为id是int类型(你定义的Student id为1、Employee为2),而compare()是std::string的成员函数,int类型没有这个方法。如果id是类的成员变量,也可以用方法1的思路,给基类加虚函数getId(),子类返回对应id值,然后排序时直接比较整数大小(return a->getId() < b->getId();)即可。

内容的提问来源于stack exchange,提问作者Gigea Nicusor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:15:16