C++定义比较函数的几种方法
为了说明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; }