【发布时间】:2021-06-25 07:19:39
【问题描述】:
res 是 string 但我无法排序。 res.begin(), res.end() 不工作了,我该怎么办?
//for example:
input: a = 13; b = 17
sort before : 1314151617
sort after : 1111134567
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void test3 () {
int a, b;
cin >> a >> b;
int l =0;
string res;
for (int i=a; i<=b; i++) {
res = res + to_string(a + l);
l++;
}
sort (res.begin(), res.end());
}
int main () {
test3();
return 0;
}
【问题讨论】:
-
对于输入
13 1,for循环不运行,因为13 <= 1为假。所以,你对一个空字符串进行排序。你怎么知道它不起作用?您不会在前后打印字符串。 -
sort()功能正常,上面的输入法有问题 -
@mch OP 希望它按降序排列。
-
从你的标题,
std::sort (res.rbegin(), res.rend());或更好的std::sort (res.begin(), res.end(), std::greater<>{});。
标签: c++ string algorithm sorting vector