Search code examples
c++booststdmapboost-multi-index

how to get an intersection of a boost::multi_index container


I want to get an intersection of 4 indexes of type ordered_non_unique the fastest possible way. Is such an multi_index-intersection faster than a 4 times nested std::map? Is there's a possibility to use something like an std::map().emplace().

Here's my code.

#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>

using boost::multi_index_container;
using namespace boost::multi_index;

struct Kpt {
    Kpt(float _x0, float _x1, float _y0, float _y1)
      : x0_(_x0),x1_(_x1),y0_(_y0),y1_(_y1) {
    }
    friend std::ostream& operator<<(std::ostream & _os, Kpt const & _kpt) {
        _os
            << "\nx0 " << _kpt.x0_ << ","
            << " y0 " << _kpt.y0_ << ","
            << " x1 " << _kpt.x1_ << ","
            << " y1 " << _kpt.y1_ << std::endl
        ;
        return _os;
    }
    float x0_;
    float x1_;
    float y0_;
    float y1_;
};

struct x0_{};
struct x1_{};
struct y0_{};
struct y1_{};

typedef multi_index_container <
    Kpt
  , indexed_by <
        ordered_non_unique <
            tag<x0_>,BOOST_MULTI_INDEX_MEMBER(Kpt,float,x0_)
        >
      , ordered_non_unique <
            tag<x1_>,BOOST_MULTI_INDEX_MEMBER(Kpt,float,x1_)
        >
      , ordered_non_unique <
              tag<y0_>,BOOST_MULTI_INDEX_MEMBER(Kpt,float,y0_)
          >
      , ordered_non_unique <
              tag<y1_>,BOOST_MULTI_INDEX_MEMBER(Kpt,float,y1_)
          >
    >
> Kpts;

int main() {
    Kpts kpts;
    for (int i=0; i<1000000; ++i) {
        if (i%10000==0) std::cout << "." << std::flush;
        kpts.insert(Kpt(0.1,0.1,0.1,0.1));
    }
}

Solution

  • OK, now I understand you'd like to search 4-dimensional points in the region [x0,x0+d]×[x1,x1+d]×[y0,y0+d]×[y1,y1+d], right?

    Well, I'm afraid to say Boost.MultiIndex is not the right tool for that, as obtaining the intersection of ranges in indices #0, #1, #2, #3 can only be done by scanning one of the ranges (say #0) and manually verifying if the traversed points' remaining coordinates (x1, y0, y1) lie within the area of interest (std::set_intersection does not even apply here as it requires that compared ranges be sorted by the same criterion, which is not the case for our indices).

    boost::geometry::index::rtree or some similar spatial data structure are likely, as you point out, to be better suited for this job.