【发布时间】:2016-02-03 20:57:06
【问题描述】:
我使用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) );
}
【问题讨论】:
-
顺序对您有什么影响?
-
如果您使用的是无序集,您是否已经决定不关心迭代器通过数据的顺序?您是否尝试过使用
const_iterator?发生了什么?什么有效?什么没有? -
unordered_set的用法似乎很奇怪。您使用整个 Node 作为自己的密钥的动机是什么?
标签: c++ c++11 unordered-set