gpt4 book ai didi

c++ - 在 shared_ptr 的 unordered_set 中找到一个值

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:48 25 4
gpt4 key购买 nike

我想在 unordered_set 中找到一个值,但是失败了:

typedef std::shared_ptr<int> IntPtr;

std::unordered_set<IntPtr> s;
s.insert(std::make_shared<int>(42));

bool found = s.find(std::make_shared<int>(42)) != s.end();
cout<<std::boolalpha<<found<<endl; // false

已尝试跟随但仍然无法正常工作。

namespace std {
template <> struct hash<IntPtr> {
size_t operator()(const IntPtr& x) const noexcept {
return std::hash<int>()(*x);
}
};
}

知道如何让它发挥作用吗?

最佳答案

您存储了一个指向整数的指针。当您在集合中查找项目时,您不是在比较(指向的)整数,而是在比较指针本身。

当你为搜索分配一个new指针到一个new整数对象时,它不会比较相等,因为它是一个不同的整数对象(即使它存储相同的值)。

您的选择是:

  1. 不要在集合中存储指向整数的指针,只需直接存储整数。

    然后,你的键是 42,搜索 42 会找到它,因为整数是按值比较的

  2. 存储指针并使用自定义哈希和比较器来比较指向的整数而不是指针。

    你不应该(尝试)用你的散列特化来污染 std 命名空间,无论如何它是不够的(散列用于桶查找,但键仍然与 KeyEqual 进行比较 在桶内)。只需为您的容器指定它们。

#2 的示例代码:

#include <cassert>
#include <memory>
#include <unordered_set>

struct Deref {
struct Hash {
template <typename T>
std::size_t operator() (std::shared_ptr<T> const &p) const {
return std::hash<T>()(*p);
}
};
struct Compare {
template <typename T>
size_t operator() (std::shared_ptr<T> const &a,
std::shared_ptr<T> const &b) const {
return *a == *b;
}
};
};

int main() {
std::unordered_set<std::shared_ptr<int>> sp;
auto p = std::make_shared<int>(42);
sp.insert(p);
assert(sp.find(p) != sp.end()); // same pointer works
assert(sp.find(std::make_shared<int>(42)) == sp.end()); // same value doesn't

// with the correct hash & key comparison, both work
std::unordered_set<std::shared_ptr<int>, Deref::Hash, Deref::Compare> spd;
spd.insert(p);
assert(spd.find(p) != spd.end());
assert(spd.find(std::make_shared<int>(42)) != spd.end());
}

关于c++ - 在 shared_ptr 的 unordered_set 中找到一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32613304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com