sort() 中的比较函数 compare 要声明为静态成员函数或全局函数,不能作为普通成员函数,否则会报错。
cmpChar实现功能:大写字母大于小写字母,小写字母按 a-z 升序,大写字母按 A-Z 升序
声明为静态成员函数
class Solution {
public:
void CharacterSort(const vector<char> e_char)
{
cout << "before:" << endl;
for (auto i : e_char) {
cout << i;
}
cout << endl;
std::sort(e_char.begin(), e_char.end(), cmpChar);
cout << "after:" << endl;
for (auto i : e_char) {
cout << i;
}
cout << endl;
}
private:
static bool cmpChar(const char &a, const char &b)
{
if (a <= 'Z' && b >= 'a')
return false;
else if (b <= 'Z' && a >= 'a')
return true;
else
return a < b;
}
};
输入:
vector e_char = {‘C’,‘B’,‘A’,‘c’,‘b’,‘a’};
输出:
before:
CBAcba
after:
abcABC
lamda表达式
class Solution {
public:
void CharacterSort(const vector<char> e_char)
{
cout << "before:" << endl;
for (auto i : e_char) {
cout << i;
}
cout << endl;
auto cmpChar = [](const char &a, const char &b) {
if (a <= 'Z' && b >= 'a')
return false;
else if (b <= 'Z' && a >= 'a')
return true;
else
return a < b;
};
std::sort(e_char.begin(), e_char.end(), cmpChar);
cout << "after:" << endl;
for (auto i : e_char) {
cout << i;
}
cout << endl;
}
using namespace std;
bool cmpChar(const char &a, const char &b)
{
if (a <= 'Z' && b >= 'a')
return false;
else if (b <= 'Z' && a >= 'a')
return true;
else
return a < b;
}
class Solution {
public:
void CharacterSort(const vector<char> e_char)
{
cout << "before:" << endl;
for (auto i : e_char) {
cout << i;
}
cout << endl;
std::sort(e_char.begin(), e_char.end(), cmpChar);
cout << "after:" << endl;
for (auto i : e_char) {
cout << i;
}
cout << endl;
}