向泛型算法传递函数可以是:
- 静态类成员函数
- 非类成员函数(在类之外定义的函数)
- lambda函数
1. 静态类成员:
头文件:
class PrintMinNumber
{
public:
PrintMinNumber();
virtual ~PrintMinNumber();
string solution(vector<int> numbers);
static bool cmp(int it1, int it2);
protected:
private:
};
cpp文件:
string PrintMinNumber::solution(vector<int> numbers)
{
string ret;
int length = numbers.size();
if(length <= 0)
return ret;
sort(numbers.begin(), numbers.end(),cmp);
for(vector<int>::iterator it = numbers.begin(); it != numbers.end(); it++)
{
stringstream ss;
ss << *it;
ret.append(ss.str());
}
return ret;
}
bool PrintMinNumber::cmp(int it1, int it2)
{
stringstream ss;
ss << it1;
string input1 = ss.str();
ss << it2;
string input2 = ss.str();
return (input1+input2) < (input2+input1);
}
2. 非类成员函数
bool cmp1(int it1, int it2)
{
stringstream ss;
ss << it1;
string input1 = ss.str();
ss << it2;
string input2 = ss.str();
return (input1+input2) < (input2+input1);
}
string PrintMinNumber::solution(vector<int> numbers)
{
string ret;
int length = numbers.size();
if(length <= 0)
return ret;
sort(numbers.begin(), numbers.end(),cmp1);
for(vector<int>::iterator it = numbers.begin(); it != numbers.end(); it++)
{
stringstream ss;
ss << *it;
ret.append(ss.str());
}
return ret;
}