gpt4 book ai didi

c++ - 使用 std::sort 对 std::list 进行排序

转载 作者:IT老高 更新时间:2023-10-28 23:03:24 27 4
gpt4 key购买 nike

Possible Duplicate:
Sort list using stl sort function
why only std::list::sort()?

我的问题是我们可以使用 std::sort 函数对两个 std::list 进行排序吗?我有 2 个字符串列表

  std::list<std::string>list1, list2;
.....//entering values to list
std::sort(list1.begin(), list1.end());

std::sort(list2.begin(), list2.end());

当我对这些列表进行排序时,我遇到了错误。我尝试使用 std::vector,此时排序有效。

错误是这样的

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xutility(1158) : see declaration of 'std::operator -' 1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\algorithm(3642): error C2784: '_Base1::difference_type std::operator - (const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'std::_List_iterator<_Mylist>' 1> with 1> [ 1> _Mylist=std::_List_val> 1> ]

我要知道只有 std::sort 支持列表?

最佳答案

您不能使用 std::sortstd::list 进行排序,因为 std::sort 要求迭代器是随机的访问,而 std::list 迭代器只是双向的。

但是,std::list 有一个成员函数 sort 可以对其进行排序:

list.sort();
// if you want to use a comparator different from the default one:
// list.sort(comparator);

关于c++ - 使用 std::sort 对 std::list 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10652674/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com