C ++ STL:根据另一个的内容自定义排序一个向量 [英] C++ STL: Custom sorting one vector based on contents of another

查看:180
本文介绍了C ++ STL:根据另一个的内容自定义排序一个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是最好的例子。我有两个向量/列表:

This is probably best stated as an example. I have two vectors/lists:

People = {Anne, Bob, Charlie, Douglas}
Ages   = {23, 28, 25, 21}

我想根据年龄排序人物, code> sort(People.begin(),People.end(),CustomComparator),但我不知道如何编写 CustomComparator 来查看Ages而不是People。

I want to sort the People based on their ages using something like sort(People.begin(), People.end(), CustomComparator), but I don't know how to write the CustomComparator to look at Ages rather than People.

推荐答案

而不是创建两个单独的矢量/列表,这是为了创建一个包含名称和年龄的对象的单个向量/列表:

Instead of creating two separate vectors/lists, the usual way to handle this is to create a single vector/list of objects that include both names and ages:

struct person { 
    std::string name;
    int age;
};

要根据年龄进行排序,请定义一个比较器来查看年龄:

To get a sort based on age, define a comparator that looks at the ages:

struct by_age { 
    bool operator()(person const &a, person const &b) { 
        return a.age < b.age;
    }
};

然后你的排序看起来像这样:

Then your sort would look something like:

std::vector<person> people;
// code to put data into people goes here.

std::sort(people.begin(), people.end(), by_age());

编辑:至于在定义运算符< 对于类,或者使用一个单独的比较器对象,如我上面所述,它主要是一个问题,是否有一个单一的排序是明显的这个类。

As for choosing between defining operator< for the class, or using a separate comparator object as I have above, it's mostly a question of whether there's a single ordering that's "obvious" for this class.

在我看来,排序人们并不一定总是按年龄排序。然而,如果在你的程序的上下文中,很显然,排序的人将按年龄来完成,除非你明确指定,否则,实现比较将是有意义的 person :: operator< 而不是在一个单独的比较类中我以上做的方式。

In my opinion, it's not necessarily obvious that sorting people would always happen by age. If, however, in the context of your program it would be obvious that sorting people would be done by age unless you explicitly specified otherwise, then it would make sense to implement the comparison as person::operator< instead of in a separate comparison class the way I've done it above.

这篇关于C ++ STL:根据另一个的内容自定义排序一个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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