c++ - 对 std::unordered_set 中元素的指针/引用

标签 c++ c++11 unordered-set

我正在使用 std::unordered_set存储我的数据对象。 但是现在我想创建一个指向它们的指针/引用,例如(没有散列函数......):

struct Node
{
  Node* parent;
  ...
};
std::unordered_set<Node> list;

是否可以使用 std::unordered_set<Node>::const_iterator ? 如果 (不删除元素!) 迭代器“排序”发生变化,我不确定如何找出这些信息?

更新更多细节以便更好地理解:

我选择 std::unordered_set 是因为查找时间恒定。 要提高我的 C++ 技能,最好知道要更改什么。

#include <iostream>
#include <string>
#include <stdint.h>
#include <vector>

#include <unordered_set>


struct Link;
struct Node
{
    uint32_t id;
    std::unordered_set<Link> link;

    Node(uint32_t id) : id(id)
    {
    };

    bool operator==(Node const& rhs)
    {
        return id == rhs.id;
    }
};

struct Link
{
    Node* parent;
    uint32_t param1; // ..... and more

    bool operator==(Link const& rhs)
    {
        return parent == parent.rhs && param1 == rhs.param1;
    }
}


namespace std
{
    template<> struct hash<Node>
    {
        size_t operator()(Node const& node) const
        {
            return hash<uint32_t>()(node.id);
        }
    };

    template<> struct hash<Link>
    {
        size_t operator()(Link const& link) const
        {
            return  hash<uint32_t>()(link.param1) ^ hash<Node>()(*link.parent);
        }
    };    
}

int main()
{
    std::unordered_set<Node> nodes;
    nodes.emplace( Node(1) );
    nodes.emplace( Node(2) );
    nodes.emplace( Node(3) );    
}

最佳答案

你可以有指向 Node 的指针unordered_set 内的对象.但是这些指针必须是 Node const* (即 const )。

即使对 unordered_set 进行了插入指针不会失效。例如,您可以将这些指针存储在另一个 unordered_set<Node const*> 中。作为:

std::unordered_set<Node, hasher> s{{1}, {2}, {3}};
std::unordered_set<Node const*> s_ptr;

for(auto &&i : s) {
  s_ptr.insert(&i);
}

Live Demo

关于c++ - 对 std::unordered_set 中元素的指针/引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35187544/

相关文章:

c++ - 聚合方法中的 sigsegv 错误

c++ - 因为 std::swap(s1, s2) 就足够了,所以 string::swap 可以忽略吗?

c++ - clear() 是否影响 std::unordered_set 的桶计数?

python - 从 Python 导出 Tensorflow 图以在 C++ 中使用

C++ 和 Qt - 从页面内容编码

c++ - 解决简单哈希表中的内存泄漏和语法问题

c++ - 我可以 std::find stringstream 中的字符串吗?

c++ - 为什么在类中初始化的非整数静态数据成员必须是 constexpr?

c++ - 如何释放unordered_set的内存?

c++ - 无序集的编译问题