【问题标题】:Sort string array with sort, error reported用sort对字符串数组排序,报错
【发布时间】:2021-08-15 12:12:59
【问题描述】:

当我将“

第一个问题

代码:

#include <bits/stdc++.h>
using namespace std;

int main(){
    string s[30];
    int n = 20;

    for(int i = 0; i < n; i++){
        s[i] = "3";
    }
    sort(s, s + n, [](string a, string b){
        return a <= b;
    });

    return 0;
}

错误:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

第二个问题

代码:

#include <bits/stdc++.h>
using namespace std;

int main(){
    string s[30];
    int n = 20;

    for(int i = 0; i < n; i++){
        s[i] = "3";
    }
    sort(s, s + n, [](const string& a, const string& b){
        return a <= b;
    });

    return 0;
}

错误:

Segmentation fault

【问题讨论】:

标签: c++ string sorting


【解决方案1】:

你应该使用'<=。关键是:

比较函数对象(即满足 如果第一个参数是,则返回 true 小于(即先于)第二个。

std::sort

所以&lt;= 将满足要求,(当且仅当所有被排序的值都存在差异时)但它不是为此目的而= 部分在所有元素不同的情况下只是多余的并且可能未定义,所有元素都相同。 &lt; 被评估并控制排序。不要使用&lt;= 排序比较功能需要&lt;&gt;。见C++ named requirements: Compare

Do not #include <bits/stdc++.h>。使用适当的头文件来提供程序所需的原型和功能。另见Why is “using namespace std;” considered bad practice?

综合考虑并稍微整理一下示例,您可以这样做:

#include <iostream>
#include <string>
#include <algorithm>

#define MAXS 30         /* if you need a constant, #define one (or more) */

int main () {
    
    std::string s[MAXS] {};

    for(int i = 0; i < MAXS; i++) {         /* loop assigning to all strings */
        s[i] = std::to_string (i % 10);     /* convert (i % 10) to string */
    }
    /* sort the array of std::string */
    std::sort (s, s + MAXS, [](const std::string& a, const std::string& b){
                               return a < b; });
    
    for (const auto& st : s)                /* output results */
        std::cout << st << '\n';
}

查看一下,如果您还有其他问题,请告诉我。

【讨论】:

  • 如果&lt;= 可以工作,那为什么不...?
  • 在原始问题中,您有一个 std::string 数组仅部分初始化(30 个元素中的前 20 个),20 的范围全部用"3" 填充。当调用sort 时,它们已经处于排序状态,因此您不会期望任何更改。在那里,= 只会导致无意义的元素交换,这些元素永远不会结束——因为什么都不会改变。
  • 编辑让这变得更好,谢谢。我不知道你为什么推荐一个全局的#define,但是当一个本地的constconstexpr 可以工作并且不会污染整个全局命名空间时。就其他常见的新手陷阱提供很好的建议来避免,然后添加你自己的一个,这似乎很奇怪;-)
  • constexpr 100% 没问题——老 C 程序员 :)
  • const 在这种情况下也应该可以正常工作,早在constexpr 之前。
【解决方案2】:

您应该查看第 6 行的逻辑和 for 循环中两种不同数据类型的值,它们如何相加比较?

【讨论】:

  • 这是关键,为什么所有元素都一样会出现问题?也可以比较相等的元素
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
相关资源
最近更新 更多