Re: Looking for container like std::map but for ranges
In article <48e7a2e6$0$29281$4d3ebbfe@news1.pop-hannover.net>,
guido@thisisnotatest.de says...
Hi,
I'm looking for a container class that can map whole ranges of keys to
objects - something like std::map, but not only for individual values for
the key, but for whole ranges.
The container just uses the comparison you define for it. To work with
ranges like this, all values within a range will be considered equal.
#include <map>
#include <iostream>
#include <string>
struct cmp {
int range(unsigned value) const {
static const unsigned bounds[] = { 11, 50001, 60000};
for (int i=0; i<3; i++)
if (value < bounds[i])
return i;
return -1;
}
public:
bool operator()(unsigned a, unsigned b) const {
return range(a) < range(b);
}
};
int main() {
std::map<unsigned, std::string, cmp> values;
values[5] = "String 1";
values[20] = "string 2";
values[55000] = "String 3";
std::cout << "Values[10] = " << values[10] << "\n";
return 0;
}
If you have very many ranges to deal with, you'd proably want to use a
binary search instead of a linear searhc, but for only three ranges it
wouldn't really make any noticeable difference.
--
Later,
Jerry.
The universe is a figment of its own imagination.