为了说明C++定义比较函数的几种方法,下面将以sort函数为例进行说明。

1.默认的内置比较函数,将按照对象内定义的<运算符由小到大排序

#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std;

int main()
{
    vector<string> vec{"Hello", "World!", "Zhang San", "Li Si", "C++", "C"};
    sort(vec.begin(), vec.end());
    copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, "\n"));
    return 0;
}

2.使用自定义的比较函数cmp,将按照从大到小的顺序排序

bool cmp(const string & a, const string & b)
{
    return a > b;
}
int main()
{
    vector<string> vec{"Hello", "World!", "Zhang San", "Li Si", "C++", "C"};
    sort(vec.begin(), vec.end(), cmp);
    copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, "\n"));
    return 0;
}

3.使用C++内置的Function object

int main()
{
    vector<string> vec{"Hello", "World!", "Zhang San", "Li Si", "C++", "C"};
    sort(vec.begin(), vec.end(), greater<string>());
    copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, "\n"));
    return 0;
}

4.使用C++11新支持的lambda表达式

int main()
{
    vector<string> vec{"Hello", "World!", "Zhang San", "Li Si", "C++", "C"};
    sort(vec.begin(), vec.end(), [](const string & a, const string & b) {return a > b;});
    copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, "\n"));
    return 0;
}

5.重载()运算符,即自定义一个Function object

class cmp{
public:
    bool operator () (const string & a, const string & b) {
        return a > b;
    }
};
int main()
{
    vector<string> vec{"Hello", "World!", "Zhang San", "Li Si", "C++", "C"};
    sort(vec.begin(), vec.end(), cmp());
    copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, "\n"));
    return 0;
}



相关文章:

  • 2021-11-01
  • 2021-06-06
  • 2022-12-23
  • 2022-12-23
  • 2021-11-08
  • 2021-10-12
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-02
  • 2022-12-23
  • 2021-12-21
  • 2022-01-01
相关资源
相似解决方案