Reputation: 33
I want to sort an array of numeric strings and I am using the sort() function from the C++ library.
I am passing to the function a third parameter to tell how to compare the strings but I can't get it right.
Can somebody help me?
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
bool howToCompare(string i, string j) {
if(i.length() > j.length()) {
return i > j;
}
else if(i.length() < j.length()) {
return i < j;
}
else {
for(int k = 0; k < i.length(); k++) {
if(i[k] - '0' < j[k] - '0') {
return i < j;
}
else if (i[k] - '0' > j[k] - '0'){
return i > j;
}
}
}
return i == j;
}
int main() {
int n;
cin >> n;
string array[n];
for(int i = 0; i < n; i++) {
cin >> array[i];
}
sort(array, array + n, howToCompare);
for(int i = 0; i < n; i++) {
cout << array[i] << endl;
}
return 0;
}
Upvotes: 0
Views: 267
Reputation: 73376
The problem is that your howToCompare()
doesn't fit the requirements of std::sort()
which expects to have a strict ordering. The boolean that it returns should always correspond to the clause "less than".
Here a correction of your original code that works, assuming that the difference of length between two strings is nod caused by leading zeros:
bool howToCompare(string i, string j) {
if(i.length() > j.length()) {
return false;
}
else if(i.length() < j.length()) {
return true;
}
else {
for(int k = 0; k < i.length(); k++) {
if(i[k] < j[k] ) {
return true;
}
else if (i[k] > j[k] ){
return false;
}
}
}
return false;
}
Here an online demo (you can also try your old function with some trace of what's going on on all the compares)
Here an online demo that checks if strings are numeric only, that handles different size and potential leading 0, and uses a vector container instead of an array.
Upvotes: 1