我试图更好地理解 unordered_set 。主要是,据我了解,unordered_set 中的元素在 equal_to 运算符之前应该是唯一的。因此,我决定通过一小段代码来测试一下
#include <iostream>
#include <unordered_set>
using namespace std;
struct m_int
{
int x;
};
// template specialization for std::hash
template<>
struct std::hash<m_int>
{
std::size_t operator()(m_int const& x) const noexcept
{
return hash<int>{}(x.x);
}
};
//template specialization for std::equal_to
template<>
struct std::equal_to<m_int>
{
bool operator()(const m_int &lhs, const m_int &rhs) const
{
return abs(lhs.x-rhs.x)<=3;
}
};
int main() {
unordered_set<m_int> m={{1},{2},{3},{4}};
for(auto&x:m)
cout<<x.x<<' ';
cout<<endl;
cout<<m.count({2})<<endl;
// your code goes here
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我最初的想法是1会插入2,3会但会插入4。
我得到的输出是 …