8

I'm trying to find an efficient C++ interval tree implementation (mostly likely based on red black trees) without a viral or restrictive license. Any pointers to a clean lightweight standalone implementation? For the use case I have in mind, the set of intervals is known at the outset (there would be say a million) and I want to be able to quickly obtain a list of intervals that overlap a given interval. Thus the tree once built will not change -- just needs rapid queries.

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185

3 Answers3

5

I've written a template-based interval tree implementation in C++, https://github.com/ekg/intervaltree. MIT license. Enjoy.

Erik Garrison
  • 1,607
  • 14
  • 12
3

The C++ standard library offers red/black trees std::map, std::multimap, std::set and std::multiset.

Really, I can't think of any way to handle this more efficiently than to keep a std::map of iterator pairs, and passing those iterator pairs to upper_bound() and lower_bound(). You'd want the iterator pairs to be kept in a map themselves so that you could easily zero in on which pairs are likely to be in the interval (if the beginning iterator in the "candidate interval" comes after the end of the given interval you're looking at, then you can skip checking that -- and all later -- iterator pairs).

Max Lybbert
  • 18,615
  • 3
  • 41
  • 68
  • Could you explain this a little more on how map/set can be implemented as Interval Trees ? – Kyuubi Aug 05 '13 at 10:33
  • @Kyuubi: I suggested implementing an interval tree with a `std::map`/`std::set` (that is, starting with `std::map`/`std::set` and ending with an interval tree; **NOT** starting with an interval tree and implementing a `std::map`, `std::set`). – Max Lybbert Aug 06 '13 at 05:45
  • @Kyuubi Going off of memory, I believe the idea was simply that you had (1) a collection of things, (2) a list of intervals in that collection that you were looking at, (3) you defined the intervals with `begin` and `end` iterators. So, using a `std::map`, you could simply have the `begin` iterator be the key, and the corresponding `end` iterator be the value. Using this, you can't find all intervals you want in one shot, but you can narrow down the intervals you need to filter through. – Max Lybbert Aug 06 '13 at 05:47
1

There's also a C# implementation of Interval tree at this link. It's easy enough to translate to C++ for those in need

plasmacel
  • 7,355
  • 5
  • 42
  • 87
cos
  • 87
  • 1