根据类中的变量对类的向量进行排序 [英] sorting a vector of classes based on a variable in the class

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

问题描述

我有一个类,其中存储有类型为int的变量.然后,我创建了一个向量,其中包含此类,然后需要对其进行排序. 但是,我的问题来自于这样一个事实,即我需要使用该类内部存储的int值以升序对向量进行排序.

I have a class in which there is a variable of type int stored inside. I have then created a vector which holds this class in it, which I then need to sort. My problem however stems from the fact that I need to sort the vector using the values of the int stored inside of this class in accending order.

我看过C ++内置的std::sort()类,但似乎无法使它正常工作.我也看过诸如将自定义对象的向量排序的帖子. 并尝试使用它,但无济于事.

I have looked at the std::sort() class built into C++ but cannot seem to get this to work. I have also looked at posts such as, Sorting a vector of custom objects and have tried to use this, but with no avail.

请注意,这是我的第一篇文章,因此,如果我做错了任何事情,请告诉我,以便我纠正问题.

As a side note, this is my first post, so if I am doing anything wrong, please let me know so that I can rectify the problem.

推荐答案

如果您有类对象的向量

std::vector<MyClass> objs;

要排序的变量是

MyClass.value

那么你可以

std::sort(objs.begin(),
          objs.end(),
          [](const MyClass& lhs, const MyClass& rhs)
{
    return lhs.value < rhs.value;
});

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

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