I'm trying to implement the maximizing salary problem. Like if we are given two numbers 2
and 21
then the resultant number should be 221
not 212
. I implemented the code and it works very well for small inputs. The code uses C++ std::sort
with a simple comparator function. For big inputs like for 100 it fails and gives following error.
stderr:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Here's my code:
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
using std::max;
bool comp(const string &a, const string &b) {
string combo1 = a+b;
string combo2 = b+a;
return combo1>=combo2;
}
string largest_number(vector<string> a) {
std::sort(a.begin(), a.end(), comp);
string result = "";
for (int i=0; i< a.size(); i++) {
result = result + a[i];
}
return result;
}
int main() {
int n;
std::cin >> n;
vector<string> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
std::cout << largest_number(a);
}
For the following inputs it gives error.
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
How do I solve this issue? I read some probable solutions and it was something about NULL pointers which I couldn't understand.