Ai
9 Star 26 Fork 5

boldness2012/C++47Code

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
unordered_set.cc 2.80 KB
一键复制 编辑 原始数据 按行查看 历史
boldness2012 提交于 2023-04-13 16:54 +08:00 . 1
#include <iostream>
#include <unordered_set>
using std::cout;
using std::endl;
using std::unordered_set;
template <typename Container>
void display(const Container &con)
{
for(auto &elem : con)
{
cout << elem << " ";
}
cout << endl;
}
void test()
{
//unordered_set的特征
//1、key值是唯一的,不能重复
//2、key值是没有顺序的
//3、底层使用的是哈希
unordered_set<int> number = {1, 3, 5, 5, 7, 2, 9, 8, 4, 5};
display(number);
}
class Point
{
public:
Point(int ix = 0, int iy = 0)
: _ix(ix)
, _iy(iy)
{
}
int getX() const
{
return _ix;
}
int getY() const
{
return _iy;
}
~Point()
{
}
friend std::ostream &operator<<(std::ostream &os, const Point &rhs);
friend bool operator==(const Point &lhs, const Point &rhs);
private:
int _ix;
int _iy;
};
std::ostream &operator<<(std::ostream &os, const Point &rhs)
{
os << "(" << rhs._ix
<< ", " << rhs._iy
<< ")";
return os;
}
//标准命名空间的扩展
namespace std
{
//类模板的特化
template <>
struct hash<Point>
{
size_t operator()(const Point &rhs) const
{
cout << "size_t std::hash::operator()(const Point &) const" << endl;
return (rhs.getX() << 1)^(rhs.getY() << 2);
}
};//end of struct hash
}//end of namespace std
//针对于hash设置的函数对象形式
struct HasherPoint
{
size_t operator()(const Point &rhs) const
{
cout << "size_t HasherPoint::operator()(const Point &) const" << endl;
return (rhs.getX() << 1)^(rhs.getY() << 2);
}
};
//标准命名空间的扩展
namespace std
{
//类模板的特化
template <>
struct equal_to<Point>
{
bool operator()( const Point& lhs, const Point& rhs ) const
{
cout << "bool std::equal_to::operator()()" << endl;
return (lhs.getX() == rhs.getX()) && (lhs.getY() == rhs.getY());
}
};
}//end of namespace std
//只针对equal_to的函数对象形式
struct EqualToPoint
{
bool operator()( const Point& lhs, const Point& rhs ) const
{
cout << "bool EqualToPoint::operator()()" << endl;
return (lhs.getX() == rhs.getX()) && (lhs.getY() == rhs.getY());
}
};
bool operator==(const Point &lhs, const Point &rhs)
{
cout << "friend bool operator==(const Point &, const Point &) " << endl;
return (lhs._ix == rhs._ix) && (lhs._iy == rhs._iy);
}
void test2()
{
/* unordered_set<Point> number = { */
/* unordered_set<Point, HasherPoint, EqualToPoint> number = { */
unordered_set<Point, HasherPoint> number = {
Point(1, 2),
Point(-1, 2),
Point(1, -2),
Point(1, 2),
Point(3, 2),
Point(5, -2),
};
display(number);
}
int main(int argc, char **argv)
{
test2();
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/boldness2012/cpp47_code.git
git@gitee.com:boldness2012/cpp47_code.git
boldness2012
cpp47_code
C++47Code
master

搜索帮助