boost::基于多索引范围的复合键

问题描述 投票:0回答:1

我正在尝试在多索引容器上执行复合范围查询,但遇到了一些问题。举个最简单的例子:


// This is my object
struct Obj {
  int one;
  int two;
  int three;
};

typedef boost::multi_index_container<
  Obj,
  boost::multi_index::indexed_by<
    boost::multi_index::ordered_non_unique<
      boost::multi_index::composite_key<
        Obj,
        boost::multi_index::member<Obj, int, &Obj::one>,
        boost::multi_index::member<Obj, int, &Obj::two>
      >
    >
  >
> object_multi;

int main() {
    object_multi objects;

    // For example
    objects.insert({1, 1, 3});
    objects.insert({1, 5, 6});
    objects.insert({2, 2, 4});
  
    auto& index = objects.get<0>();
    // get elements where one = [1, 3] AND two [1, 2]
    auto lower = index.lower_bound(boost::make_tuple(1, 1));
    auto upper = index.lower_bound(boost::make_tuple(3, 2));

    for (auto it = lower; it != upper; ++it) 
        std::cout << it->one << ", " << it->two << ", " << it->three << std::endl;
    
  
  return 0;
}

我希望只得到

Obj{1, 1, 3}
Obj{2, 2, 4}
,这是唯一匹配两个搜索条件的,但该代码还返回
Obj{1, 5, 6}
,其中 2 不是 <= 2.

我错过了什么?可以实现我的需求吗?

提前致谢。

c++ boost boost-multi-index
1个回答
0
投票

您已经构建了一个“复合键”有序索引。指标值为:

{1, 1}
{1, 5}
{2, 2}

然后您可以查询 {1, 1} 和 {3, 2} 之间的值。索引中的所有值都在该范围内,因为索引在检查第二个组件之前先检查第一个组件。换句话说,这就像拥有数字 [1.1, 1.5, 2.2] 并要求 1.1 和 3.2 之间的数字。都在这个范围内。

根据您的评论,您可能认为索引是单独检查每个组件并返回结果的交集的东西:

// get elements where one = [1, 3] AND two [1, 2]

但事实并非如此。

© www.soinside.com 2019 - 2024. All rights reserved.