思路:
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
bool cmp(string a, string b)
{
return a+b > b+a;
}
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string>v;
for (int i = 0; i < nums.size(); i++)
{
string temp = to_string(nums[i]);
v.push_back(temp);
}
sort(v.begin(), v.end(), cmp);
string ret;
for (int i = 0; i < v.size(); i++)
{
ret += v[i];
if (v[0] == "0")
break;
}
return ret;
}
};
int main()
{
string ans;
int a[2]={12,3};
vector<int> nums;
for (int i=0; i<2; i++)
{
nums.push_back(a[i]);
}
Solution s;
ans=s.largestNumber(nums);
cout<<ans<<endl;
return 0;
}
sort(first, second, cmp): cmp为布尔类型函数,若返回值为真,则first排在second之前。
// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}