【发布时间】: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
【问题讨论】:
-
这就是
std::sort的本质,它需要less关系,不需要less or equal。您违反了此约束,因此您遇到了未定义的行为。 -
@Aconcagua 谢谢!我会仔细阅读的
-
您的第三个问题,请参阅Why should I not #include <bits/stdc++.h>?