Created
August 31, 2016 16:42
-
-
Save cdmh/3317f123785daee9a32b0a8b8453c70d to your computer and use it in GitHub Desktop.
Functions to keep a vector of pair<Key,Value> sorted by Key. Can replace a std::map for performance or space saving, depending on use case
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
// sorted vector functions | |
template<typename Key, typename T> | |
typename std::vector<std::pair<Key, T>>::iterator | |
lookup(std::vector<std::pair<Key, T>> &vec, Key key) | |
{ | |
auto const end = vec.end(); | |
auto it = lower_bound(vec.begin(), end, key, [](std::vector<std::pair<Key, T>>::value_type const &elem, Key key) { | |
return elem.first < key; | |
}); | |
if (it !=end && !(key < it->first)) | |
return it; | |
return end; | |
} | |
template<typename Key, typename T> | |
typename std::vector<std::pair<Key, T>>::const_iterator | |
lookup(std::vector<std::pair<Key, T>> const &vec, Key key) | |
{ | |
auto const end = vec.cend(); | |
auto it = lower_bound(vec.cbegin(), end, key, [](std::vector<std::pair<Key, T>>::value_type const &elem, Key key) { | |
return elem.first < key; | |
}); | |
if (it !=end && !(key < it->first)) | |
return it; | |
return end; | |
} | |
template<typename Key, typename T> | |
typename std::vector<std::pair<Key, T>>::iterator | |
insert(std::vector<std::pair<Key, T>> &vec, Key key) | |
{ | |
auto const end = vec.end(); | |
auto it = lower_bound(vec.begin(), end, key, [](std::vector<std::pair<Key, T>>::value_type const &elem, Key key) { | |
return elem.first < key; | |
}); | |
// already exists | |
if (it !=end && !(key < it->first)) | |
return it; | |
it = vec.insert(it, std::pair<Key, T>(key, T())); | |
// entries must be sorted | |
assert(std::is_sorted(vec.cbegin(), vec.cend(), [](std::vector<std::pair<Key, T>>::value_type const &a, std::vector<std::pair<Key, T>>::value_type const &b){ | |
return a.first < b.first; | |
})); | |
// entries must be unique | |
assert(vec.cend() == std::adjacent_find(vec.begin(), vec.end(), [](std::vector<std::pair<Key, T>>::value_type const &a, std::vector<std::pair<Key, T>>::value_type const &b){ | |
return a.first == b.first; | |
})); | |
return it; | |
} | |
template<typename Key, typename T> | |
T &at(std::vector<std::pair<Key, T>> &vec, Key key) | |
{ | |
return insert(vec, key)->second; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment