提问者:小点点

划分多个(可能)重叠范围的最简单算法


假设我有一个范围向量,我想将它们划分为多个分区。 注意,这与std::partition所做的不一样,后者是查找单个分区点。 我想知道是否有STL或boost(或其他)用于此?

为了说明我要问的问题,让我们从范围的向量开始:

using Index = int;

struct Range
{
   // Indexes are inclusive, meaning this specifies [lo, hi] not [lo, hi)
   Index lo;
   Index hi; // hi is always guaranteed to be greater than lo
};
std:vector<Range> ranges = { {0, 3}, 
                             {1, 5}, 
                             {2, 4} };

我想做的是有一个函数来划分范围,这样我就得到了如下所示的结果:

std::map<Index, int> my_map = partition(ranges); // <<<--- This is the function I'm seeking
                 ^
                 |
                 +-- This 'int' is the partition number

它生成的映射如下所示(给定上面的数据):

my_map = { {0, 0},    // Lower bound of 0 for partition 0, which is [0, 1)
           {1, 1},    // Lower bound of 1 for partition 1, which is [1, 2)
           {2, 2},    // Lower bound of 2 for partition 2, which is [2, 4)
           {4, 3},    // Lower bound of 4 for partition 3, which is [4, 5)
           {5, 4}, }; // Lower bound of 5 for partition 4, which is [5, ...]

现在,当我想知道某物在哪个分区中时:

Partition which(Index i)
{
    auto it = my_map.upper_bound(i);
    if (it != my_map.end())
        return (--it)->second;
    return my_map.size() - 1;
}       

共1个答案

匿名用户

似乎是Boost::ICL做到了这一点。。。 贷记@Sascha