gpt4 book ai didi

c++ - 用sort对字符串数组进行排序,报错

转载 作者:行者123 更新时间:2023-12-05 08:11:00 29 4
gpt4 key购买 nike

当我将“<=”更改为“<”时,这两个问题都得到了解决:有效!不知道为什么,有人可以回答我吗?谢谢!!!

第一个问题

代码:

#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

最佳答案

你应该使用 '<' 进行升序排序,但你可以使用 <= .关键是:

comparison function object (i.e. an object that satisfies therequirements of Compare) which returns ​true if the first argument isless than (i.e. is ordered before) the second.

std::sort

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

Do not #include <bits/stdc++.h> .使用提供程序所需的原型(prototype)和功能的正确 header 。另见 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';
}

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

关于c++ - 用sort对字符串数组进行排序,报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67718661/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com