c++ - 按一个字段对自定义对象的 vector 进行排序

标签 c++ sorting stl

如果有一个结构体:

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


}

现在假设 vector v 填充了信息,v_sortedFirstName 填充了相同的信息(指向与 v 相同的位置) >).我将如何(使用 STL 排序函数,按 firstnamev_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;
}

关于c++ - 按一个字段对自定义对象的 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921636/

相关文章:

c++ - 一个从 list<T> 转换为 vector<T> 的衬垫

c++ - 在 C++ 中模拟来自 C# 的 ContainsKey (Key) - 什么是最佳实践?

c++ - 如何从双端队列中删除随机元素

c++ - 托管 html/css/js UI 的最轻量级方式?

c# - 在 C# 中对字符串进行排序

Javascript 排序自定义比较器函数 - 对已排序的数组进行排序

c++ - std::remove 与 vector::erase 和未定义的行为

c++ - 您使用什么工具在 Linux 上开发 C++ 应用程序?

c++ - 如何为 sfml 2.0 安装 libGLEW 1.5?

c - 如何提高 C 中大数据排序的执行速度