基于不同字段的对象向量的排序功能 [英] Sorting function for a vector of objects based on different fields

查看:50
本文介绍了基于不同字段的对象向量的排序功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象向量:

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?

推荐答案

我认为以前的评论都说可以编写这样的比较函数.但是,如果我对您的理解正确,那么您希望所有4个比较都使用一个函数(也许以模板化的方式).确实,当使用成员对象指针时(是成员 function 指针,这要归功于@WhozCraig指出来):

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

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

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.

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

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

这篇关于基于不同字段的对象向量的排序功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆