如何解决C ++固定容量关联容器
我正在寻找一个不使用任何动态分配的容器,例如std::unordered_map
。我相信,对于具有固定数量的键的任何关联容器,甚至在编译时必须选择的键,都是如此。
我不是要查找constexpr
或编译时哈希映射,因为我希望能够更新映射中的值。
用例示例:
FixedCapacityMap<std::string_view,int> fruits {
{"n_apples",0},{"n_pairs",0}
}
fruits["n_apples"] += 1;
fruits["n_pairs"] += 1;
有人知道这样的库是否存在吗?如果不存在,该如何实现?
解决方法
“无动态分配”规则的必要结果是基础数据已嵌入到您的类型中,因此您还需要指定键数作为模板参数。
如果在编译时知道键,则可以在其上构造一个固定大小的哈希表。
通常,下一个最好的方法是链式哈希或二进制搜索。这是一个在std::array<std::pair<K,V>,N>
上使用二进制搜索的小型实现:
template <class K,class V,size_t N>
class FixedCapacityMap {
public:
using value_type = std::pair<K,V>;
FixedCapacityMap(std::initializer_list<value_type> init) {
assert(init.size() == N);
std::copy(cbegin(init),cend(init),begin(store));
}
V& operator[](const K& key) {
auto it = std::lower_bound(begin(store),end(store),std::pair{key,V()});
if (it == end(store) || it.first != key)
throw std::out_of_range(key);
return it.second;
}
private:
std::array<value_type,N> store;
}
,
我能够找到具有此功能的图书馆:
https://github.com/serge-sans-paille/frozen
它允许constexpr
和constinit
有序和无序的映射,并且(我新添加)能够在运行时更新值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。