给定一个元素数组,找到使用数组元素可以组成的最大可能数字。
例如:10 9
答案:910
2 3 5 78
答案:78532
100 9
答案:9100
我知道这个问题可以使用自定义字符串比较器来解决,但我不理解它是如何工作的。
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
bool compare ( string a, string b )
{
return atoi( (a+b).c_str() ) < atoi((b+a).c_str() );
}
int main()
{
vector<string> vs;
string s;
while ( cin >> s ) {
vs.push_back(s);
}
sort( vs.begin(), vs.end(), compare );
for ( int i = vs.size()-1; i >= 0; i-- ) {
cout << vs[i];
}
}
有人能提出一个算法来解决这个问题吗? 欢迎对上述比较器进行解释。 谢谢
compare()
函数。 - Gene Bushuyev