#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string TmpS;
cin >> TmpS;
stable_sort(TmpS[0], TmpS[TmpS.size()]);
}在Compiler Explorer上编译这段代码会得到以下错误:
In file included from /opt/compiler-explorer/gcc-11.1.0/include/c++/11.1.0/algorithm:62,
from <source>:2:
/opt/compiler-explorer/gcc-11.1.0/include/c++/11.1.0/bits/stl_algo.h: In instantiation of 'void std::__stable_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = char; _Compare = __gnu_cxx::__ops::_Iter_less_iter]':
/opt/compiler-explorer/gcc-11.1.0/include/c++/11.1.0/bits/stl_algo.h:5056:36: required from 'void std::stable_sort(_RAIter, _RAIter) [with _RAIter = char]'
<source>:8:16: required from here
/opt/compiler-explorer/gcc-11.1.0/include/c++/11.1.0/bits/stl_algo.h:5008:9: error: no type named 'value_type' in 'struct std::iterator_traits<char>'
5008 | _ValueType;
| ^~~~~~~~~~
/opt/compiler-explorer/gcc-11.1.0/include/c++/11.1.0/bits/stl_algo.h:5010:9: error: no type named 'difference_type' in 'struct std::iterator_traits<char>'
5010 | _DistanceType;
| ^~~~~~~~~~~~~
/opt/compiler-explorer/gcc-11.1.0/include/c++/11.1.0/bits/stl_algo.h:5011:68: error: no type named 'value_type' in 'struct std::iterator_traits<char>'
5011 | typedef _Temporary_buffer<_RandomAccessIterator, _ValueType> _TmpBuf;
| ^~~~~~~我不理解这些错误,大概是它无法推断出值和范围应该是什么类型?谷歌搜索也无济于事。为什么编译器会抛出这些错误,我该如何修复代码?
发布于 2021-07-04 01:19:31
你想要std::sort(TmpS.begin(), TmpS.end());。
std::stable_sort(TmpS.begin(), TmpS.end());也可以工作,但因为您没有提供自定义比较器,所以它会做与std::sort完全相同的事情,但速度更慢(因为稳定性保证)。
发布于 2021-07-04 01:52:23
您需要传递字符串的起始点和结束点的迭代器(准确地说,是您想要排序的字符串部分),因此您可以在此处使用begin()和end()方法
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string TmpS;
cin >> TmpS;
stable_sort(TmpS.begin(), TmpS.end());
cout << TmpS;
}发布于 2021-07-04 01:08:27
您需要传递对数据的引用,而不是值本身。
stable_sort(&TmpS[0], &TmpS[TmpS.size()]);https://stackoverflow.com/questions/68238375
复制相似问题