1

I am looking for the best way to extract objects from a large collection based on their position from two sorted parameters.

Example:

struct Object{
    Time start;
    Time end;
    //... data
};

Now, for any time t I want to quickly find all objects that "exist" within this time, i.e. t is between the objects' start and end values.

The approach I have thought of is to use:

std::multimap<Time, object*> objectsOrderedByStart;
std::multimap<Time, object*> objectsOrderedByEnd;

(multimap since there may be many objects with the same Time values, which are the sorted keys)

Every time I create an Object I add it to each multimap which automatically places the object in a sorted list for start and end.

I then "query" for my valid objects for time t by looking for all objects in objectsOrderedByStart where t>Time and objects in objectsOrderedByEnd where t<End, and then taking only those that are in both result sets. But this seems inefficient and the only technique I can think of to find the union is by going through one result set one-by-one and looking to see if that object is in the other result set.

However I suspect this is not the most efficient method. I could iterate by skipping over the elements when iterating each multimap, rather than one-by-one iteration, then fall back if I've gone too far and iterate one-by-one from the last skipping point. Alternately I could retain just one multimap and then peer inside each object to look at its end time.

But I suspect there is a better way to organize this data and find those in the range that interest me?

johnbakers
  • 24,158
  • 24
  • 130
  • 258
  • @n.m. i'm curious, how did you find that other question? it's not one of the "related" questions that appear, and searching didn't turn that up for me. Of course that question is not c++ specific, or not tagged as such, so perhaps part of the issue. – johnbakers Jun 18 '13 at 10:03
  • It is a well known problem and a relevant google search (*time interval search* I think) brings that other question up pretty high in the results. – n. m. could be an AI Jun 18 '13 at 10:31
  • @n.m. so far the method I've most been able to wrap my head around is the Augmented Interval Tree http://en.wikipedia.org/wiki/Interval_tree – johnbakers Jun 18 '13 at 10:48

2 Answers2

0

You could use two manually-sorted arrays instead of two multimaps, and then use std::lower_bound and std::upper_bound, or hand-coded binary search, to search in them.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • I think custom bsp is the way to go, in particular, an Augmented Interval Tree seems to be a good choice here – johnbakers Jun 18 '13 at 23:33
0

I think you should have a look at Boost.ICL

rectummelancolique
  • 2,247
  • 17
  • 13