我正在尝试使用唯一的数字id索引从boost::multi_index_container中检索值。我以前从未使用过boost::multi_index_container,因此我在理解它们的工作原理时遇到了一些问题。它们的工作方式看起来有点像数据库,我想做的就是通过指定id来检索一个条目。任何帮助都将不胜感激。
以下是数据类型:
typedef boost::multi_index_container<
// Multi index container holds pointers to the subnets.
Subnet6Ptr,
// The following holds all indexes.
boost::multi_index::indexed_by<
// First is the random access index allowing for accessing
// objects just like we'd do with a vector.
boost::multi_index::random_access<
boost::multi_index::tag<SubnetRandomAccessIndexTag>
>,
// Second index allows for searching using subnet identifier.
boost::multi_index::ordered_unique<
boost::multi_index::tag<SubnetSubnetIdIndexTag>,
boost::multi_index::const_mem_fun<Subnet, SubnetID, &Subnet::getID>
>,
// Third index allows for searching using an output from toText function.
boost::multi_index::ordered_unique<
boost::multi_index::tag<SubnetPrefixIndexTag>,
boost::multi_index::const_mem_fun<Subnet, std::string, &Subnet::toText>
>
>
> Subnet6Collection;Subnet6Collection对象是在DHCPv6服务器(KEA)加载其配置文件时创建的。此文件包含每个子网的可选数字ID值,数据类型为SubnetID。
我想通过指定SubnetID来检索Subnet6Ptr。
发布于 2019-07-03 19:58:46
是的,多索引可能是一个很难处理的野兽。正如我在a different answer中所写的,"Boost.Multi-index提供了一个极其可定制的界面,但代价是提供了一个极其复杂的界面。“
基本上,当您想要访问容器的内容时,您可以通过它的一个索引来访问它。因此,首先获取对要使用的索引(在本例中为带标签的SubnetSubnetIdIndexTag )的引用,然后将该索引视为容器。哪个容器取决于索引的类型。对于排序后的唯一索引(就像您的例子一样),这有点像std::map (但是迭代器只指向值),或者像std::set一样,它有一个透明的比较器,只比较in。
下面是它在代码中的样子:
Subnet6Collection coll = something();
SubnetID idToLookFor = something2();
auto& indexById = coll.index<SubnetSubnetIdIndexTag>();
auto it = index.find(idToLookFor);
if (it != index.end()) {
Subnet6Ptr p = *it;
} else {
// No such ID found
}发布于 2019-07-03 20:36:31
谢谢你的回复。
我尝试了以下方法(SubnetID只是uint32_t,所以我使用10作为测试):
SubnetID id = 10;
Subnet6Collection coll;
auto& indexById = coll.index<SubnetSubnetIdIndexTag>();
auto it = index.find(id);
if (it != index.end()) {
Subnet6Ptr p = *it;
} else {
// No such ID found
}但是它不能编译:
Opt18_lease_select.cc:38:24:错误:无效使用‘struct boost::multi_index::multi_index_container,boost::multi_index::indexed_by >,boost::multi_index::ordered_unique,boost::multi_index::const_mem_fun >,boost::multi_index::ordered_unique,boost::multi_index::const_mem_fun,&isc::dhcp::Subnet::toText>::index’
auto& indexById = coll.index<SubnetSubnetIdIndexTag>();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~Opt18_lease_select.cc:39:17:错误:没有上下文类型信息的重载函数
auto it = index.find(id);
^~~~Opt18_lease_select.cc:40:17:错误:没有上下文类型信息的重载函数
if (it != index.end()) {
^~~似乎index() find(),end()不能以这种方式使用,或者我只是遗漏了一些头文件?
https://stackoverflow.com/questions/56869509
复制相似问题