Created
May 9, 2017 21:20
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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