需要:用于维护1维区段列表的c++类
Needed: C++ class for maintaining a 1-dimensional list of extents
我正在寻找一个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;
}
}
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何维护资源管理器项目视图中当前可见的项目列表
- 在卡萨布兰卡形成编码参数的列表
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题