Skip to content

Instantly share code, notes, and snippets.

@csullivan
Created May 9, 2017 21:20
Show Gist options
  • Save csullivan/6a82f6ecbef677086cc339169c737df2 to your computer and use it in GitHub Desktop.
Save csullivan/6a82f6ecbef677086cc339169c737df2 to your computer and use it in GitHub Desktop.
A simple key-range containter. If a key is within a range, the corresponding value is returned. O(log n)
template<typename KeyType, typename ValueType>
class range_map {
public:
range_map() { ; }
range_map(std::initializer_list<std::pair<KeyType,ValueType>> list) {
for (auto& pair : list) {
keys.push_back(pair.first);
values.push_back(pair.second);
}
}
ValueType& operator[](KeyType search_key) {
auto index = std::lower_bound(keys.begin(), keys.end(), search_key) - keys.begin();
index = (index < keys.size()) ? index : keys.size()-1;
return *(values.begin() + index);
}
private:
std::vector<KeyType> keys;
std::vector<ValueType> values;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment