首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“在实例化... required ... required from here”和“没有命名的类型...”在std::stable_sort中

“在实例化... required ... required from here”和“没有命名的类型...”在std::stable_sort中
EN

Stack Overflow用户
提问于 2021-07-04 01:06:40
回答 3查看 51关注 0票数 1
代码语言:javascript
复制
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    string TmpS;
    cin >> TmpS;
    stable_sort(TmpS[0], TmpS[TmpS.size()]);
}

在Compiler Explorer上编译这段代码会得到以下错误:

代码语言:javascript
复制
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;
      |                                                                    ^~~~~~~

我不理解这些错误,大概是它无法推断出值和范围应该是什么类型?谷歌搜索也无济于事。为什么编译器会抛出这些错误,我该如何修复代码?

EN

回答 3

Stack Overflow用户

发布于 2021-07-04 01:19:31

你想要std::sort(TmpS.begin(), TmpS.end());

std::stable_sort(TmpS.begin(), TmpS.end());也可以工作,但因为您没有提供自定义比较器,所以它会做与std::sort完全相同的事情,但速度更慢(因为稳定性保证)。

票数 1
EN

Stack Overflow用户

发布于 2021-07-04 01:52:23

您需要传递字符串的起始点和结束点的迭代器(准确地说,是您想要排序的字符串部分),因此您可以在此处使用begin()和end()方法

代码语言:javascript
复制
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    string TmpS;
    cin >> TmpS;
    stable_sort(TmpS.begin(), TmpS.end());
    cout << TmpS;
}
票数 0
EN

Stack Overflow用户

发布于 2021-07-04 01:08:27

您需要传递对数据的引用,而不是值本身。

代码语言:javascript
复制
stable_sort(&TmpS[0], &TmpS[TmpS.size()]);
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68238375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档