【问题标题】:How to sort a string from bigger to smaller如何将字符串从大到小排序
【发布时间】:2021-06-25 07:19:39
【问题描述】:

resstring 但我无法排序。 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 1for 循环不运行,因为 13 &lt;= 1 为假。所以,你对一个空字符串进行排序。你怎么知道它不起作用?您不会在前后打印字符串。
  • sort()功能正常,上面的输入法有问题
  • @mch OP 希望它按降序排列。
  • 从你的标题,std::sort (res.rbegin(), res.rend()); 或更好的std::sort (res.begin(), res.end(), std::greater&lt;&gt;{});

标签: c++ string algorithm sorting vector


【解决方案1】:

您缺少比较器。默认情况下,C++ 根据&lt; 运算符对元素进行排序。如果要按降序对元素进行排序,则使用相同的代码,但提供了一个额外的比较器:

std::string s = "12341532231858092";
std::sort(s.begin(), s.end(), std::greater<char>()); // notice the 3rd argument!
std::cout << s << std::endl;

打印98855433322221110

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2020-01-30
    • 2012-11-18
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多