Register__ 2022-03-18 23:15 采纳率: 89.5%
浏览 22
已结题

C++STL unorder_set容器问题

我把想法简化成了这样:
就是我想让 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 是按怎么 来判断元素相等的?

  • 写回答

1条回答 默认 最新

  • _GX_ 2022-03-19 03:07
    关注

    达不到想要的效果是因为你实例化的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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 3月27日
  • 已采纳回答 3月19日
  • 修改了问题 3月18日
  • 创建了问题 3月18日

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵