通过结构中的变量对结构的向量进行排序? [英] Sort vector of structs by a variable within the struct?

查看:58
本文介绍了通过结构中的变量对结构的向量进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据结构,例如:

I have a struct of data, for example:

struct Data
{
string firstname;
string lastname:
string age;
}

我将每个结构都放在一个向量(VectorOfData)中.是否可以遍历此向量并按降序对向量中的每个结构进行排序?使用类似的东西:

I've placed every struct within one vector (VectorOfData). Is it possible to loop through this vector and sort each struct in the vector by descending age? using something like:

for(std::vector<Data>::const_iterator it = VectorOfData.begin(); it != VectorOfData.end(); ++it)
{

//sorting by age here?

}

我假设它不会那么简单,因为迭代器一次只访问向量中的一个结构?

I'm assuming it wouldnt be that simple because the it iterator is only accessing one struct within the vector at a time?

我意识到我甚至可以在将结构放入向量之前就可以进行排序,但是我的问题并不是那么简单.这只是我可以解释的最简单的方法.任何建议将不胜感激,谢谢

I realize i could probably do the sorting before i even put the structs in the vector, but my problem isn't that simple. This is just the simplest way i could explain it. Any advice would be much appreciated, thanks

推荐答案

您可以将std :: sort与自定义比较功能一起使用:

You can use std::sort with a custom comparison function:

bool is_younger(const Data& x, const Data& y) { return x.age < y.age; }

排序:

std::sort(VectorOfData.begin(), VectorOfData.end(), is_younger);

或者,您可以定义一个自定义的 functor (注意:这实际上是首选,因为它增加了内联的可能性,请阅读:更快的排序)

Alternatively, you can define a custom functor (note: this is actually preferred, as it increases the likelihood of inlining, read: faster sorting)

struct is_younger_functor
{
    bool operator()(const Data& x, const Data& y) const
    {
        return x.age < y.age; 
    }
};

排序:

std::sort(VectorOfData.begin(), VectorOfData.end(), is_younger_functor());

如果要为 Data 定义严格的排序关系,则应考虑将其转换为常规类型(定义运算符<,< =,==,!=,>,>=).

If you want to define a strict ordering relationship for Data, you should consider turning it into a regular type (define operators <, <=, ==, !=, >, >=).

在这种情况下,您无需定义此is_younger函子,只需使用迭代器即可调用std :: sort.

In that case, you will not need to define this is_younger functor and can call std::sort with just the iterators.

严格来说,您只需要定义运算符<对于std :: sort,但如果定义了它,则最好定义它们的其余部分.

Strictly, you only need to define operator < for std::sort, but if you define it, it is a good idea to define the rest of them.

这篇关于通过结构中的变量对结构的向量进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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