【问题标题】:boost multi index - loop through key value of specific entryboost multi index - 遍历特定条目的键值
【发布时间】:2018-04-17 11:23:57
【问题描述】:

我有一个带有 2 个索引的多索引(在实际代码中,它们属于不同类型)。

class CrUsersKeys{
  int IMSI;
  int TIMESTAMP;
}

在多索引中找到一个条目后,我就有了该条目的迭代器。

auto it = multi.GetIteratorBy<IMSI_tag>(searchKey);

现在我想遍历这个特定 (*it) 中的所有索引成员并检查它们。请注意,我不想遍历迭代器,而是通过 CrUsersKeys 的索引元素。我该怎么做?

for(key in it)
{
     if(isGoodKey(key))
         std::cout<<"key "<<key <<" is good key"<<std::endl;
}

所以它应该检查 isGoodKey((*it).IMSI) 和 isGoodKey((*it).TIMESTAMP)。 CrUsersKeys 是模板参数,所以我不知道 CrUsersKeys 的成员。

http://coliru.stacked-crooked.com/a/d97195a6e4bb7ad4的代码示例

我的多索引类在共享内存中。

【问题讨论】:

    标签: boost-multi-index


    【解决方案1】:

    您的问题与 Boost.MultiIndex 几乎没有关系,并且基本上要求一种方法来编译时迭代类的成员。如果您可以将 CrUsersKeys 定义为 std::tuple(或类似元组的类),那么您可以执行以下操作(C++17):

    编辑:展示了如何使非元组类适应框架。

    Live On Coliru

    #include <tuple>
    
    template<typename Tuple,typename F>
    bool all_of_tuple(const Tuple& t,F f)
    {
      const auto fold=[&](const auto&... x){return (...&&f(x));};
      return std::apply(fold,t);
    }
    
    #include <iostream>
    #include <type_traits>
    
    bool isGoodKey(int x){return x>0;}
    bool isGoodKey(const char* x){return x&&x[0]!='\0';}
    
    template<typename Tuple>
    bool areAllGoodKeys(const Tuple& t)
    {
      return all_of_tuple(t,[](const auto& x){return isGoodKey(x);});
    }
    
    struct CrUsersKeys
    {
      int         IMSI;
      const char* TIMESTAMP;
    };
    
    bool areAllGoodKeys(const CrUsersKeys& x)
    {
      return areAllGoodKeys(std::forward_as_tuple(x.IMSI,x.TIMESTAMP));
    }
    
    int main()
    {
      std::cout<<areAllGoodKeys(std::make_tuple(1,1))<<"\n";        // 1
      std::cout<<areAllGoodKeys(std::make_tuple(1,"hello"))<<"\n";  // 1
      std::cout<<areAllGoodKeys(std::make_tuple(1,0))<<"\n";        // 0
      std::cout<<areAllGoodKeys(std::make_tuple("",1))<<"\n";       // 0
      std::cout<<areAllGoodKeys(CrUsersKeys{1,"hello"})<<"\n";      // 1
      std::cout<<areAllGoodKeys(CrUsersKeys{0,"hello"})<<"\n";      // 0
      std::cout<<areAllGoodKeys(CrUsersKeys{1,""})<<"\n";           // 0
    }
    

    【讨论】:

    • 我不认为我会做元组,它会使代码太复杂。感谢您的回答
    • 编辑了答案以显示如何使CrUsersKeys 与提议的框架一起使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 2010-12-14
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多