【问题标题】:Sorting a vector of custom objects by one field按一个字段对自定义对象的向量进行排序
【发布时间】:2016-04-28 17:29:58
【问题描述】:

如果有结构体:

#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 排序功能,按 firstnamev_sortedFirstName 进行排序?

我在想这条线:sort(v_sortedFirstName.begin(), v_sortedFirstName.end(), pred); 应该是类似于sort(v_sortedFirstName-&gt;firstname.begin(), v_sortedFirstName-&gt;firstname.end(), pred); 的东西,但这不起作用。

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

【问题讨论】:

    标签: c++ sorting stl


    【解决方案1】:

    您的谓词必须接受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;
    }
    

    【讨论】:

    • 谢谢!所以对于const,这意味着如果有人试图修改函数中的值(如a-&gt;firstname = "John";),它不会让它发生?
    • @StacksAndParsing 没错
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多