我也成功创建了boost::multi_index
个值并插入了值。我有两个散列索引到multi_index。两者都是成员函数,但一个是唯一的,另一个是非唯一的。
我试图找出使用哈希值从容器中获取值的方法。我无法理解我应该怎么做。我在网上搜索,我看到有很多人都问过这个问题。但我不明白需要做些什么。我在C ++ 11中看到了一些解决方案,但是我没有使用C ++ 11,我也不明白它是什么。有人可以向我解释如何使用它吗?以下是我的代码,
#include "stdafx.h"
#include<multi_index_container.hpp>
#include<boost/multi_index/hashed_index.hpp>
#include<boost/multi_index/mem_fun.hpp>
#include<boost/multi_index/tag.hpp>
class RetClass
{
int a, b;
};
class StoreMe
{
RetClass ex;
std::string exStr;
int id;
public:
void setId(RetClass a)
{
ex = a;
};
virtual const RetClass& getId() const { return ex; }
virtual std::string getIdString() const { return exStr; }
int getUniqueId() const { return id; }
};
struct IndexByStringId{};
struct IndexByUniqueId{};
typedef boost::multi_index_container<
StoreMe,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<
boost::multi_index::tag<IndexByStringId>,
boost::multi_index::const_mem_fun<StoreMe, std::string, &StoreMe::getIdString>
>,
boost::multi_index::hashed_non_unique<
boost::multi_index::tag<IndexByUniqueId>,
boost::multi_index::const_mem_fun<StoreMe, int, &StoreMe::getUniqueId>
>
>
> mi_storeMe;
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
我希望能够,
请让我知道完成此操作的正确/最简单方法。我也不使用C ++ 11。
答案 0 :(得分:0)
以下是您从基于字符串的索引中检索的方式:
[tableView reloadData]
对于基于ID的索引,它非常相似:
mi_storeMe container;
std::string needle = whatToSearchFor();
auto iterator = container.get<IndexByStringId>().find(needle);
if (iterator != container.get<IndexByStringId>().end())
found(*iterator);
else
notFound();
答案使用C ++ 11中的mi_storeMe container;
RetClass needle = whatToSearchFor();
auto range = container.get<IndexByUniqueId>().equal_range(needle);
processRangeFromTo(range.first, range.second);
,这样我就可以避免拼写出所涉及的类型。如果您无法访问C ++ 11,请阅读Boost的auto
文档,自行进行类型扣除。我不能保证正确性,但我相信迭代器类型可以拼写为
multi_index
切线相关:如何在没有C ++ 11的情况下对多索引容器进行printf式调试。
首先,请记住,虽然您没有mi_storeMe::index<IndexByStringId>::type::iterator
,但您仍然可以在模板中进行类型扣除。如果函数模板可以推导出类型,则无需拼写出类型:
auto
其次,您可以轻松地遍历索引:
template <class It>
void printContainerItems(It from, It to) {
for (; from != to; ++from)
print(*from);
}
printContainerItems(container.begin(), container.end());