代码拉取完成,页面将自动刷新
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。