无法使用std::sort对std::list结构体列表排序的问题求助
问题原因及解决方案
核心问题是你误用了std::sort标准算法来排序std::list容器:
std::sort要求迭代器具备随机访问能力(比如std::vector的迭代器),但std::list的迭代器是双向迭代器,不支持it + n这类随机跳转操作,因此编译时会触发std::__list_iterator二元表达式无效的错误。- 你尝试的四种比较器写法本身没有问题,但容器与算法的搭配从根源上不兼容,所以无论用哪种比较器都会编译失败。
正确做法:使用std::list自带的sort()成员函数
std::list提供了专属的sort()成员函数,专门适配其双向迭代器特性,支持你尝试的所有比较方式:
- lambda表达式作为比较器
#include <list> struct MyStruct { int value; }; int main() { std::list<MyStruct> my_list = {{3}, {1}, {2}}; my_list.sort([](const MyStruct& a, const MyStruct& b) { return a.value < b.value; }); return 0; }
- 结构体函数对象作为比较器
#include <list> struct MyStruct { int value; }; struct CompareStruct { bool operator()(const MyStruct& a, const MyStruct& b) const { return a.value < b.value; } }; int main() { std::list<MyStruct> my_list = {{3}, {1}, {2}}; my_list.sort(CompareStruct()); return 0; }
- 在结构体中重载
<运算符
#include <list> struct MyStruct { int value; bool operator<(const MyStruct& other) const { return value < other.value; } }; int main() { std::list<MyStruct> my_list = {{3}, {1}, {2}}; my_list.sort(); // 自动使用重载的<运算符 return 0; }
- 使用静态比较函数
#include <list> struct MyStruct { int value; static bool compare(const MyStruct& a, const MyStruct& b) { return a.value < b.value; } }; int main() { std::list<MyStruct> my_list = {{3}, {1}, {2}}; my_list.sort(&MyStruct::compare); return 0; }
编译说明
保持你原来的编译命令即可:
g++ -std=c++17 do-sort.cpp -o do-sort.out
只要将代码中std::sort(my_list.begin(), my_list.end(), ...)的调用替换为my_list.sort(...)即可正常编译运行。
内容的提问来源于stack exchange,提问作者Jane Wayne
相关产品推荐
相关产品推荐

