【发布时间】:2021-04-23 16:37:21
【问题描述】:
我的目标是编写一个像 unordered_map 一样工作的类,但保持元素的插入顺序,同时仍然允许通过键进行 O(1) 查找。
我的做法如下:
// like unordered_map but keeps the order of the elements for iteration
// implemented as a vector with a unordered_map for constant time lookups
// consider if element removal is needed, since it is O(N) because of the use of a vector of elements
template <typename KEY, typename VAL>
struct ordered_map {
struct KeyValue {
KEY key;
VAL value;
};
std::vector<KeyValue> elements; // KeyValue pairs in order of insertion to allow iteration
std::unordered_map<KEY, int> indexmap; // key -> index map to allow O(1) lookup, is there a way to avoid the redundant key?
//...
}
但是我有一个问题,在我的方法中,我想使用“外部”存储的键来查找索引映射(在基于映射中索引值的元素向量中)。
std::sort 例如允许传入一个比较器,
但 unordered_sap 似乎没有类似的东西。
我真的无法在网上找到有关如何完成此操作的任何信息,但我可能使用错误的术语进行搜索。
stl完全支持这种方法吗?
或者我需要两次存储密钥, 我想避免这种情况,因为键可以是堆对象,例如 std::strings。
编辑:unordered_map 代替 unordered_set 不起作用
【问题讨论】:
-
我猜
indexmap持有密钥的哈希值,因为它使用的是std::size_t。那么使用外部存储的密钥有什么问题呢?您只需散列密钥并检查它是否存在于indexmap? -
也许boost::multi_index 可以帮忙? Example
-
KeyValue很小,因此同时拥有std::set<KeyValue>和std::unordered_set<KeyValue>应该不是问题。另一方面,我闻到了XY problem,所以请解释一下为什么你有这个要求。 -
我可能会改变你的方法。使用
unordered_map保存值,使用带有指针的vector来跟踪订单。 -
如果您希望
unordered_set<size_t>实际上是unordered_map<SomeKey, size_t>,那么编写它就不会那么混乱了。然后SomeKey可以只是std::reference_wrapper<KEY>- 尽管我同意将 KEY 保留在地图中并管理外部迭代器序列更明智。
标签: c++ stl unordered-map