需要:用于维护1维区段列表的c++类

Needed: C++ class for maintaining a 1-dimensional list of extents

本文关键字:列表 c++ 段列表 用于 维护 1维 需要      更新时间:2023-10-16

我正在寻找一个c++类,可以维护一个1维的区段列表。

每个区定义为一个(start,len)对。

我希望能够向列表中添加额外的区段,并使它们自动合并。也就是说,如果我们在列表中有(0,5)(10,5),并且添加了(5,5),则新列表应该只包含(0,15)

区段永远不会从列表中删除。

这样的东西存在吗?

谢谢。

您要找的是Boost.Icl。它完全符合你的描述。

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

下面是一个简单间隔容器的实现示例:

#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
using std::vector;
using std::pair;
using std::make_pair;
typedef pair<int, int> interval;    
struct interval_container
{
    void add(int start, int len)
    {
        _data.emplace_back( make_pair(start, len) );
    }
    void consolidate()
    {
        // sort intervals first by start then by length
        std::sort(_data.begin(), _data.end());
        // create temp data
        vector<interval> consolidated;
        // iterate over all sorted intervals
        for(const interval& i : _data)
        {
            int start = i.first;
            int len = i.second;
            // special case: first interval
            if (consolidated.empty())
            {
                consolidated.emplace_back(i);
            }
            // all other cases
            else
            {
                // get last interval in the consolidated array
                interval& last = consolidated.back();
                int& last_start = last.first;
                int& last_len = last.second;

                // if the current interval can be merged with the last one
                if ((start >= last_start) and (start < (last_start + last_len)))
                {
                    // merge the interval with the last one
                    last_len = std::max(last_len, (start + len - last_start));
                }
                // if the current interval can't be merged with the last one
                else
                {
                    consolidated.emplace_back(i);
                }
            }
        }
        // copy consolidated data
        _data = consolidated;
    }

    vector<interval>& data() { return _data; }
private:
    vector<interval> _data;
};

int main()
{
    interval_container intervals;
    intervals.add(0, 2);
    intervals.add(1, 3);
    intervals.add(5, 3);
    intervals.consolidate();
    int c(0);
    for(interval i : intervals.data())
    {
        std::cout << (c++) << ": from " << i.first << " to " << (i.first + i.second) << std::endl;
    }
}