从boost::multi_index中获取值
Get values from a boost::multi_index
我已经成功创建了一个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;
}
我想要能够,
- 获取非唯一Id映射到 的值
- 获取唯一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();
对于基于id的索引,它非常相似:
mi_storeMe container;
RetClass needle = whatToSearchFor();
auto range = container.get<IndexByUniqueId>().equal_range(needle);
processRangeFromTo(range.first, range.second);
答案使用c++ 11中的auto
,这样我就可以避免拼写所涉及的类型。如果您无法访问c++ 11,请通过阅读Boost的multi_index
文档自己进行类型推断。我不能保证其正确性,但我相信迭代器类型可以拼写为
mi_storeMe::index<IndexByStringId>::type::iterator
切题相关:如何在没有c++ 11的情况下进行多索引容器的打印式调试。
首先,请记住,虽然没有auto
,但在模板中仍然有类型推导。如果函数模板可以推断出类型,则无需拼写类型:
template <class It>
void printContainerItems(It from, It to) {
for (; from != to; ++from)
print(*from);
}
printContainerItems(container.begin(), container.end());
第二,可以很容易地遍历索引:
const mi_Container::index<IndexByIdString>::type& index = container.get<IndexByIdString>();
for (
mi_Container::index<IndexByIdString>::type::iterator it = index.begin(), end = index.end();
it != end;
++it
)
{
operate_on(*it);
}
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- Boost Spirit,获取迭代器内部语义动作
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 通过迭代器获取 set 元素的"index"
- 在c++ 11 foreach循环中获取index