报错代码
#include<iostream>
#include<list>
#include<random>
#include<algorithm>
using namespace std;
int main(){
list<int> a;
for (int i=0;i<10;++i) a.push_back(rand());
for (auto num: a) cout << num << ' ';
sort(a.begin(),a.end());
cout << endl;
for (auto num: a) cout << num << ' ';
system("pause");
return 0;
}
报错
报错信息很长,这里截取一些部分,以便搜索:
In instantiation of ‘void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator; _Compare = __gnu_cxx::__ops::_Iter_less_iter]’
stl_algo.h:4828:18: required from 'void std::sort(_RAIter, _RAIter) [with _RAIter = std::_List_iterator]
stl_algo.h:1968:22: error: no match for ‘operator-’ (operand types are ‘std::_List_iterator’ and ‘std::_List_iterator’)
1968 | std::__lg(__last - __first) * 2,
stl_bvector.h:214:39: note: no known conversion for argument 1 from ‘std::_List_iterator’ to ‘const std::_Bit_iterator_base&’
214 | operator-(const _Bit_iterator_base& __x, const _Bit_iterator_base& __y)
原因
list容器不支持随机访问,不能直接使用algorithm的sort
解决方案
使用list专用的sort,即写成 a.sort()(类似python),具体如下,成功运行
#include<iostream>
#include<list>
#include<random>
#include<algorithm>
using namespace std;
int main(){
list<int> a;
for (int i=0;i<10;++i) a.push_back(rand());
for (auto num: a) cout << num << ' ';
// `list` type container should use its specialized sort function
a.sort();
cout << endl;
for (auto num: a) cout << num << ' ';
system("pause");
return 0;
}