In my current project processes, distinguishable intervals, needs to be combined, if they are adjacent.
For this purpose I wanted to use the fantastic boost::icl library. Every process can be uniquely identified by its id.
First I'm adding some intervals to my interval_map. Now I wanted to accomplish two things:
- Iterate over all occurring process-types (Here id=1,4,7)
- Secondly, iterate over all processes being in a certain subset of kinds, in such a way that merging of overlapping intervals is automatically done.
This is what I got so far:
#include <iostream>
#include <set>
#include <boost/icl/interval_map.hpp>
#include "boost/icl/closed_interval.hpp"
struct Process {
int id;
};
bool operator==(const Process& p, const Process& q) {
return p.id == q.id;
}
bool operator<(const Process& p, const Process& q) {
return p.id < q.id;
}
std::ostream& operator<<(std::ostream& str, const Process& p) {
str << "Process{" << p.id << "}";
return str;
}
int main(int, char**) {
using namespace boost::icl;
interval_map<double, std::set<Process>> imap;
imap.add({ interval<double>::closed(0., 4.),{ Process{ 4 } } });
imap.add({ interval<double>::closed(2., 6.),{ Process{ 1 } } });
imap.add({ interval<double>::closed(4., 9.),{ Process{ 4 } } });
imap.add({ interval<double>::closed(8., 8.),{ Process{ 7 } } });
for (auto&& iter : imap) {
std::cout << iter.first << " - " << iter.second<< std::endl;
}
for (auto iter : find(imap, { Process{4} })) { // How to implement find on codomain
// Should print:
// [0.,4.] - { Process{4}}
// [4.,9.] - { Process{4}}
std::cout << iter.first << " - " << iter.second << std::endl;
}
}
First, an observation, since the intervals are closed,
[0,4]and[4,6]aren't actually adjacent, but overlapping. Did you meanright_open?Second, the interval map models a function, the mapping is not guaranteed to be injective.
In the limited scope of your example, it seems you'd rather invert the datastructure, to arrive at:
This results in:
Which is what I think you meant with "in such a way that merging of overlapping intervals is automatically done".
Having Both
Of course you can derive the inverse mappings from the original data-structure:
See it Live On Coliru
More Notes
Querying multiple keys in the domain is directly supported, see a good assortion of pointers here:
You can always construct your own data-structure that affords bi-directional indexes, such as shown e.g.