从boost::multi_index中获取值

Get values from a boost::multi_index

本文关键字:获取 index boost multi      更新时间:2023-10-16

我已经成功创建了一个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;
}

我想要能够,

  1. 获取非唯一Id映射到
  2. 的值
  3. 获取唯一Id映射到
  4. 的值(如果存在)
请告诉我完成这件事的正确/最简单的方法。我也不使用c++ 11

如何从基于字符串的索引中检索:

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::iterat‌​or it = index.begin(), end = index.end();
  it != end;
  ++it
)
{
  operate_on(*it);
}