您的位置:首页 > 编程语言 > C语言/C++

一个sample学会使用c++比较函数对象和hash函数对象

2016-07-13 23:27 393 查看
/*
1、自定义hash函数对象用于unordered_set中
2、自定义Compare函数对象用于排序
3、学习使用优先级队列priority_queue
*/

#include <iostream>
#include <unordered_set>
#include <algorithm>
#include <queue>
#include <iterator>

using namespace std;

//已知0 <= x, y < 100
class point
{
public:
int x;
int y;
point(int _x, int _y) : x(_x), y(_y) {}
point(const point& p) : x(p.x), y(p.y) {}
point& operator=(const point& pt)
{
x = pt.x;
y = pt.y;
return *this;
}
bool operator==(const point& pt) const
{
return pt.x == x && pt.y == y;
}
bool operator<(const point& pt) const
{
return x < pt.x;
}
bool operator>(const point& pt) const
{
return y > pt.y;
}
friend ostream& operator<<(ostream& os, point p);
};
ostream& operator<<(ostream& os, point p)
{
os << "[" << p.x << ", " << p.y << "]";
return os;
}

class compare_point_x
{
public:
bool operator()(const point& pt1, const point& pt2)
{
return pt1.x < pt2.x;
}
};

class compare_point
{
public:
bool operator()(const point& pt1, const point& pt2) const
{
return pt1 == pt2;
}
};

class hash_point
{
public:
size_t operator()(const point& pt) const
{
return pt.x * 100 + pt.y;
}
};

int main()
{
vector<point> points = {{1, 2}, {2, 3}, {1, 2}, {1, 3}, {3, 2}, {1, 2}, {3, 2}};

//对points数组按照x坐标从小到大排序
//传给sort函数的是对象
//使用less构造函数对象的前提是point必须实现operator<()
std::sort(points.begin(), points.end(), std::less<point>());
// std::sort(points.begin(), points.end(), compare_point_x());//自定义比较函数对象
/*std::sort(points.begin(), points.end(),
[](point &pt1, point &pt2) {return pt1.x < pt2.x;});//使用正则表达式
*/
std::copy(points.begin(), points.end(), ostream_iterator<point>(cout, "\n"));
cout << endl;

//利用set去除重复的point
//因为hash值相等的两个对象不一定相等,所以需要定义一个比较函数对象
//使用equal_to生成比较函数对象,必须实现operator==
//unordered_set<point, hash_point, std::equal_to<point>> point_set;
unordered_set<point, hash_point, compare_point> point_set;//使用自定义的函数对象
for (auto p : points)
{
point_set.insert(p);
}
for (auto p : point_set)
{
cout << p << endl;
}

cout << endl;

//利用priority_queue排序
//priority_queue<point, vector<point>, less<point>> q;//最大堆,要求实现operator<()
priority_queue<point, vector<point>, greater<point>> q;//最小堆,要求实现operator>()
// priority_queue<point, vector<point>, compare_point_x> q;
for (auto p : points)
{
q.push(p);
}
while (!q.empty())
{
cout << q.top() << endl;
q.pop();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息