Sorting function for a vector of objects based on different fields

最后都变了- 提交于 2020-02-25 04:41:47

问题


I have a vector of objects:

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

vector<Student> s;

Is there any way to write ONE general (maybe template) function to sort this vector (or array) based on different fields instead of writing four different functions?


回答1:


I think the previous comments all said that it is possible to write such a comparison function. But if I understand you correctly, you want one function for all 4 comparisons (maybe in a templated way). There is indeed, when using member object pointers (EDIT: was member function pointers, thanks to @WhozCraig for pointing it out):

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

Note that templating wouldn't even be necessary if all your member variables were of the same type. You could also provide an overload for Comparator<int> that default initializes member with &Student::age since there is only one int member, this would reduce the writing effort a bit.

But I think that concerning runtime speed, a lambda in place could be faster.



来源:https://stackoverflow.com/questions/59130612/sorting-function-for-a-vector-of-objects-based-on-different-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!