我想要一个list对象的stl ,每个对象包含两个对象int.之后我想在第一个值之后用stl :: sort对列表进行排序int.如何告诉sort函数它应该在第一个之后排序int?
Ker*_* SB 30
您可以指定自定义排序谓词.在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; });
Run Code Online (Sandbox Code Playgroud)
在旧版本的C++中,您必须编写适当的函数:
bool compFirst(const ipair & a, const ipair & b) { return a.first < b.first; }
thelist.sort(compFirst);
Run Code Online (Sandbox Code Playgroud)
(相反,如果ipair您当然可以拥有自己的数据结构;只需相应地修改比较函数即可访问相关数据成员.)
最后,如果这是有道理的,您还可以为自定义类配备一个operator<.这允许您在任何有序的上下文中自由使用该类,但一定要了解其后果.