我把想法简化成了这样:
就是我想让 unordered_set存放 int*类型,但是 equal 我写的是当指针中的 两个数据相同的时候算相等
可是达不到想要的效果
class eq{
public:
bool operator()(const int* x,const int* y) const {
return *x == *y;
}
};
int main(){
int a = 10;
unordered_set<int*,hash<int*>,eq> st;
st.insert(new int(10));
//如果满足要求的话,虽然a和 那个 new 出来的int 虽然 不是 一个地址,但是 值是相同的。应该是能找的啊?
if(st.find(&a) == st.end()) cout<<"no found\n";
我就是想让他 虽然放的是指针,查找元素也能是O1的
所以 这个set 是按怎么 来判断元素相等的?
达不到想要的效果是因为你实例化的std::unordered_set
不满足UnorderedAssociativeContainer
的约束条件:
其中一条是如果两个键值相等,那么它们的哈希值也相等。
你可以用下面结构体替换std::hash<int*>
来满足上面的约束条件。
struct my_hash
{
size_t operator()(const int *x) const
{
return std::hash<int>{}(*x);
}
};
https://en.cppreference.com/w/cpp/container/unordered_set
std::unordered_set
meets the requirements of Container, AllocatorAwareContainer, UnorderedAssociativeContainer.
https://en.cppreference.com/w/cpp/named_req/UnorderedAssociativeContainer
If two Keys are equal according to Pred, Hash must return the same value for both keys.