一个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; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 在命令行用 sort 进行排序
- c语言实现hashmap(转载)
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- Linux Shell - 如何使用sort与uniq命令删除重复的文本行
- share_ptr的几个注意点
- Redis sort 排序命令详解
- 批处理命令教学之字符串排序(sort)
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Ruby中Hash的11个问题解答
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- mysql Sort aborted: Out of sort memory, consider increasing server sort buffer size的解决方法
- Ruby简明教程之数组和Hash介绍
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析