按一个字段对自定义对象向量进行排序

Sorting a vector of custom objects by one field

本文关键字:对象 自定义 向量 排序 字段 一个      更新时间:2023-10-16

如果有一个结构:

#include <algorithm>
#include <vector>
#include <iomanip>
#include <string>
using namespace std;
bool pred(string *a, string *b){
    return *a < *b;
}
struct Student {
    int ID;
    int age;
    double gpa;
    string firstname;
    string lastname;
};
int main () {
    vector<Student*>v;
    vector<Student*>v_sortedFirstName;
    //both filled with same information
    // sort v_sortedFirstName by first name
    sort(v_sortedFirstName.begin(), v_sortedFirstName.end(), pred);

}

现在假设向量v被填充有信息,而v_sortedFirstName被填充有相同的信息(指向与v相同的点)。如何(使用STL排序函数,按名字v_sortedFirstName进行排序?

我在想这句话:sort(v_sortedFirstName.begin(), v_sortedFirstName.end(), pred);应该是类似sort(v_sortedFirstName->firstname.begin(), v_sortedFirstName->firstname.end(), pred);的东西,但这不起作用。

另外,如果你们不介意的话,我想坚持上面的谓词函数,不要使用Lambda,因为我还没有学会。

谓词必须接受Student *而不是string *:

bool pred(Student *a, Student *b){
    return a->firtname < b->firtsname;
}

注意,如果您不打算将数据更改参数类型修改为const Student *,这将使您的代码更干净、更安全(如果您将代码放在pred中,错误地尝试修改该结构,则编译器将拒绝编译,并且很容易检测并修复该错误):

bool pred(const Student *a, const Student *b){
    return a->firtname < b->firtsname;
}