是否可以将forward_list插入unordered_map中
Is it possible to insert a forward_list into a unordered_map?
我对重新发明车轮没有兴趣。我喜欢保持代码非常紧凑,并且容器是我喜欢使用的东西,因此我不必一行实现所有内容。那么可以一起使用这两个容器吗?
显然可以。但是,考虑Boost Multi-Index。
demo
活在coliru
#include <unordered_map>
#include <forward_list>
#include <string>
struct Element {
int id;
std::string name;
struct id_equal final : private std::equal_to<int> {
using std::equal_to<int>::operator();
bool operator()(Element const& a, Element const& b) const { return (*this)(a.id, b.id); };
};
struct name_equal final : private std::equal_to<std::string> {
using std::equal_to<std::string>::operator();
bool operator()(Element const& a, Element const& b) const { return (*this)(a.name, b.name); };
};
struct id_hash final : private std::hash<int> {
using std::hash<int>::operator();
size_t operator()(Element const& el) const { return (*this)(el.id); };
};
struct name_hash final : private std::hash<std::string> {
using std::hash<std::string>::operator();
size_t operator()(Element const& el) const { return (*this)(el.name); };
};
};
int main() {
using namespace std;
forward_list<Element> const list { { 1, "one" }, { 2, "two" }, { 3, "three" } };
{
unordered_map<int, Element, Element::id_hash, Element::id_equal> map;
for (auto& el : list)
map.emplace(el.id, el);
}
{
unordered_map<std::string, Element, Element::name_hash, Element::name_equal> map;
for (auto& el : list)
map.emplace(el.name, el);
}
}
带有多索引的演示
这实现了相同的目标,但是:
- 就地(没有容器的副本)
- 索引始终是同步
- 没有手动自定义哈希/平等函数对象
活在coliru
#include <string>
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
struct Element {
int id;
std::string name;
};
namespace bmi = boost::multi_index;
using Table = bmi::multi_index_container<Element,
bmi::indexed_by<
bmi::hashed_unique<bmi::tag<struct by_id>, bmi::member<Element, int, &Element::id> >,
bmi::hashed_non_unique<bmi::tag<struct by_name>, bmi::member<Element, std::string, &Element::name> >
>
>;
int main() {
using namespace std;
Table const list { { 1, "one" }, { 2, "two" }, { 3, "three" } };
for (auto& el : list.get<by_name>())
std::cout << el.id << ": " << el.name << "n";
for (auto& el : list.get<by_id>())
std::cout << el.id << ": " << el.name << "n";
}
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 预处理器:插入结构名称中的前一个行号
- 在未初始化映射的情况下,将值插入到映射的映射中
- 如何在c++中只将键插入到bimap的一侧
- 如何将结构插入到集合中并打印集合的成员
- C++json插入数组
- Visual Studio 2019:插入多个C++风格的单行注释
- nlohmann-json将一个数组插入到另一个数组中
- 有效地使用std::unordered_map来插入或增加键的值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 正在插入动态数组
- 插入或删除时获取usb的dos_name
- 叮叮当当在修复时插入多个"覆盖"说明符
- 链表c++插入,所有情况都已检查,但没有任何工作
- 将重物插入std::map
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 在数字之间插入 + 或 - 符号以使其等于整数
- 在字符串中插入空格
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?