创建和管理查找容器的正确方法
Correct way to create and manage look up containers
为
实例创建查找映射的正确方法。我有一个定义节点的结构如下
struct Node
{
int32_t id;
std::string name;
...
}
我想创建 2 个查找地图,基于 ID 和另一个基于名称。节点中还有其他属性也需要查找映射,但这些属性是动态的,因此并非每个 Node 实例都会在这些附加映射中具有查找条目。
只需一张查找地图,我计划创建类似的东西
typedef std::unoredered_map<int32_t, std::unique_ptr <Node> > NodesById;
我的理由只是我可以通过erase
或[id] = new 'overwrite!'
操作将其删除,而不必担心。但是我怎样才能添加相同的节点实例来表示另一个映射
typedef std::unoredered_map<std::string, std::unique_ptr <Node> > NodesByName;
我无法将相同的节点实例放入unique_ptr。所以我的问题是将 Node 实例存储到多个查找表中并仍然实现智能内存管理的正确方法是什么。
使用 boost::multi_index
:
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <string>
#include <cassert>
struct Node {
int32_t id;
std::string name;
Node(int32_t id, std::string name)
: id(id)
, name(move(name))
{}
// Just to demonstrate that Node doesn't need to be copyable/moveable.
Node(Node const&) = delete;
Node& operator=(Node const&) = delete;
};
namespace mi = boost::multi_index;
using NodeSet = mi::multi_index_container<
Node
, mi::indexed_by<
mi::hashed_unique<mi::member<Node, int32_t, &Node::id>>
, mi::hashed_unique<mi::member<Node, std::string, &Node::name>>
>
>;
int main() {
NodeSet s;
s.emplace(1, "Alice");
s.emplace(2, "Bob");
assert(s.find(1)->name == "Alice");
assert(mi::get<0>(s).find(1)->name == "Alice"); // Same as above.
assert(mi::get<1>(s).find("Alice")->id == 1);
}
按值存储比在其中存储unique_ptr
更有效。由于NodeSet
不需要Node
可复制或可移动,因此没有必要在此处使用unique_ptr
。
相关文章:
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 在 C++/CLI 中从本机转换为管理无符号短的最快方法
- 有没有更好的方法来制作事件管理器
- C++ |方法范围指针管理
- 创建和管理查找容器的正确方法
- 使用 SIMD 管理累积(单个)值的清理代码循环的方法是什么
- 建议在我的C 库中管理版本的方法
- 您是否知道使用非恢复构建方法来管理构建的任何构建工具
- C++ - 使用std::vector和相关内存管理的正确方法
- C++会话管理方法
- 公开对象管理器对象的可接受方法?
- 管理客户端在 C 套接字中突然断开连接的好方法
- 在 Linux 上管理共享库的常用方法是什么?
- glut32.dll 缺少错误.一种在非管理访问计算机上摆脱它的方法
- 编写SQLite管理器类:可行的方法
- 在资源管理器左窗格上两次调用Windows 7外壳扩展dll Initialize方法
- 我们应该在Qt中使用哪种内存管理方法
- 在工厂中管理类实例的更好方法是什么
- 在C++11中,用什么方法对数组进行简单的范围管理是最干净的
- 方法使用文件管理器创建一个空目录