interval range tree datastructure c++

梦想的初衷 提交于 2019-12-13 15:04:11

问题


I have a requirement where I have to update the color of a graphical frontend based on some attribute value.The attribute value has different ranges ....say -30 to -45, -60 to -80 and so on.....So, I needed a datastaructure where I could store these ranges(prefill them)....And When I do determine the point , I would like to know the range in which this point falls either in O(1) Time or O(logN) time....So, My Query would consist of a single point and the output should be a unique range containing that point...

I am confused between range trees and segment trees....i want to build the tree on top of c++ stl map.


回答1:


What you need is called interval tree. http://en.wikipedia.org/wiki/Interval_tree. Unfortunately you can't use std::set<> to get O(log N) insert, remove and query, because tree node needs to contain additional data. You can read about them here http://syedwaqarahmad.webs.com/documents/t.cormen-_introduction_to_algorithms_3rd_edition.pdf chapter 14.3.

Instead you can use boost. It has interval container library.

http://www.boost.org/doc/libs/1_46_1/libs/icl/doc/html/index.html




回答2:


Maybe this library can help you: https://github.com/ekg/intervaltree




回答3:


If I understand you correctly, you can du this quite easily with std::set:

#include <iostream>
#include <set>


struct Interval {
    int min;
    int max;
};

struct ComInt {
    bool operator()(const Interval& lhs, const Interval& rhs){
        return lhs.max < rhs.min;
    }
};

std::set<Interval, ComInt> intervals = { { -10, -5 }, { -4, 4 }, { 5, 10 } };


int main() {
    int point = 3;
    Interval tmp = { point, point };

    auto result=intervals.find(tmp);
    if (result != intervals.end()) {

        std::cout << "Min:" << result->min << " - Max:" << result->max << std::endl;
    } else {
        std::cout << "No matching Interval found" << std::endl;
    }
}

of course you should build a wrapper class around it



来源:https://stackoverflow.com/questions/28053727/interval-range-tree-datastructure-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!