指针/ std :: unordered_set中元素的引用

时间:2016-02-03 20:57:06

标签: 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) );    
}

2 个答案:

答案 0 :(得分:0)

您可以指向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

答案 1 :(得分:0)

在插入期间发生重新散列时,无序容器中的迭代器会失效。我不会试图预测或避免重复。只要您不插入新项目,迭代器就会保持有效。您可以删除现有项目。

请注意,即使发生重新散列,值也不会移动。在删除该特定项目之前,指针和引用不会失效。这意味着您可以Node* parent或类似。

目前还不清楚您的数据结构是什么。我假设您希望将节点存储在unordered_set(或多个集合)中,并且节点除此之外还具有parent关系。它可以使用指针或引用,而不是迭代器。您需要的唯一更改是添加一个const:const Node *parent。如果在将其插入集合后需要更改Node,则可以通过指针(unique_ptr等)存储它们,或者将unordered_map视为不可变部分作为键。< / p>

相关问题