Both problems are solved when I change "<=" to "<": it worked! I don't know why, can someone answer me? Thanks!!!
code:
#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;
}
error:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
code:
#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;
}
error:
Segmentation fault
You should use '<' for ascending sort, but you can use <=. The key is:
comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if the first argument is less than (i.e. is ordered before) the second.
std::sort
So <= will satisfy the requirement, (if and only if there are differences in all values being sorted) but it was not intended for that purpose and the = part is simply superfluous in the case all elements are different and likely undefined where all elements are the same. The < is evaluated and controls the sort. Don't use <= the sort compare function requires < or >. See C++ named requirements: Compare
Do not #include <bits/stdc++.h>. Use the proper headers that provide the prototypes and functionality necessary for your program. See also Why is “using namespace std;” considered bad practice?
Taking both into consideration and cleaning up the example a bit, you could do:
#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';
}
Look things over and let me know if you have further questions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With