C++ 对自定义类型的列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8121837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:02:39  来源:igfitidea点击:

Sorting a list of a custom type

c++stl

提问by Christian

I want to have a stl listof objects where each object contains two int's. Afterwards I want to sort the list with stl::sort after the value of the first int. How do I tell the sort function that it's supposed to sort after the first int?

我想要一个 stllist对象,其中每个对象都包含两个int。之后,我想在 first 的值之后使用 stl::sort 对列表进行排序int。我如何告诉排序函数它应该在第一个之后排序int

回答by Kerrek SB

You can specify a custom sort predicate. In C++11 this is best done with a lambda:

您可以指定自定义排序谓词。在 C++11 中,这最好用 lambda 来完成:

typedef std::pair<int, int> ipair;
std::list<ipair> thelist;

thelist.sort([](const ipair & a, const ipair & b) { return a.first < b.first; });

In older versions of C++ you have to write an appropriate function:

在旧版本的 C++ 中,您必须编写适当的函数:

bool compFirst(const ipair & a, const ipair & b) { return a.first < b.first; }

thelist.sort(compFirst);

(Instead if ipairyou can of course have your own data structure; just modify the comparison function accordingly to access the relevant data member.)

(相反,如果ipair您当然可以拥有自己的数据结构;只需相应地修改比较函数即可访问相关数据成员。)

Finally, if this makes sense, you can also equip your custom class with an operator<. That allows you to use the class freely in any ordered context, but be sure to understand the consequences of that.

最后,如果这是有道理的,您还可以为您的自定义类配备operator<. 这允许您在任何有序上下文中自由使用该类,但请务必了解其后果。

回答by thiton

std::list::sort has a one-argument form, with the first argument being the comparison function.

std::list::sort有一个单参数形式,第一个参数是比较函数。

回答by shuttle87

You can do something like this:

你可以这样做:

typedef std::pair<int,int>;
list<my_type> test_list;

bool my_compare (my_type a, my_type b)
{
    return a.first < b.first;
}

test_list.sort(my_compare);

If the type was a struct or class it would work something like this:

如果类型是结构体或类,它会像这样工作:

struct some_struct{
    int first;
    int second;
};

list<some_struct>  test_list;

bool my_compare (const some_struct& a,const some_struct& b)
{
    return a.first < b.first;
}

test_list.sort(my_compare);

Or alternatively you can define operator <for your struct and just call test_list.sort()

或者,您可以operator <为您的结构定义并调用test_list.sort()