I want to sort a string vector for an exercise. These string has only digits from 0 to 9 like [ 10 2 1 9 91 ] and I want to sort as [ 9 91 2 1 10 ] to reach the largest number ( 9912110 ). I did the following code using the sort
function
#include <algorithm>
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
bool compare(string i1, string i2)
{
int a, b;
int i = 0;
int min_len = (i1.length() > i2.length()) ? i2.length(): i1.length();
while(i < min_len) {
a = (int) (i1.at(i) - '0');
b = (int) (i2.at(i) - '0');
if (a != b)
break;
i++;
}
if (a > b)
return true;
if (a < b)
return false;
if (i1.length() > i2.length())
return false;
return true;
}
int main() {
int n;
std::cin >> n;
vector<string> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
sort(a.begin(), a.end(), compare);
}
The problem is that when I execute with arguments:
100
2 8 2 3 6 4 1 1 10 6 3 3 6 1 3 8 4 6 1 10 8 4 10 4 1 3 2 3 2 6 1 5 2 9 8 5 10 8 7 9 6 4 2 6 3 8 8 9 8 2 9 10 3 10 7 5 7 1 7 5 1 4 7 6 1 10 5 4 8 4 2 7 8 1 1 7 4 1 1 9 8 6 5 9 9 3 7 6 3 10 8 10 7 2 5 1 1 9 9 5
gives me the following error:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted
But if I execute with 99 and I delete the last number it works fine. Also gives the same error if I try with more than 100 (like 101 or 102 ...). I suppose that the error is in the compare
function.
Edited :
bool compare(const std::string& i1, const std::string& i2)
{
int i = 0;
int min_len = (i1.length() > i2.length()) ? i2.length(): i1.length();
while (i < min_len) {
int a = (int) (i1.at(i) - '0');
int b = (int) (i2.at(i) - '0');
if (a > b)
return true;
if (a < b)
return false;
i++;
}
return (i1.length() < i2.length());
}