基于不同字段的对象向量的排序函数

use*_*666 1 c++ struct function vector member-variables

我有一个对象向量:

struct Student{   
  string name;   
  string id;   
  string major;
  int age;
};

vector<Student> s;
Run Code Online (Sandbox Code Playgroud)

有没有办法编写一个通用(可能是模板)函数来根据不同的字段对这个向量(或数组)进行排序,而不是编写四个不同的函数?

n31*_*159 5

我想之前的评论都说可以写出这样的比较函数。但是,如果我理解正确的话,您需要一个函数用于所有 4 个比较(可能以模板方式)。确实有,当使用成员对象指针时(编辑:是成员函数指针,感谢@WhozCraig 指出):

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

struct Student {
    std::string name;
    std::string id;
    std::string major;
    int age;
};

template<typename T>
struct Comparator {
    const T Student::* member;

    bool operator()(const Student& stu1, const Student &stu2) const
    {
        return stu1.*member < stu2.*member;
    }

};


int main()
{
    Comparator<int> cint{&Student::age};
    Comparator<std::string> cstring{&Student::name};

    std::vector<Student> vec = {{"Paul", "P", "Mathematics", 42}, {"John", "J", "Computer Science", 43}};

    std::sort(begin(vec), end(vec), cint);
    for(auto &s: vec)
    {
        std::cout << s.age << "\n";
    }

    std::sort(begin(vec), end(vec), cstring);
    for(auto &s: vec)
    {
        std::cout << s.name << "\n";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您的所有成员变量都属于同一类型,则甚至不需要模板。您还可Comparator<int>以为默认初始化提供一个重载member&Student::age因为只有一个int成员,这会减少一点编写工作。

但我认为关于运行时速度,适当的 lambda 可能会更快。