Updating map utility to accept a generic container

This commit is contained in:
Dan Paulat 2023-05-22 22:44:52 -05:00
parent 69730515aa
commit fc3b1f2d2e

View file

@ -8,19 +8,20 @@ namespace scwx
namespace util namespace util
{ {
template<class Key, class T, class ReturnType = std::map<Key, T>::const_pointer> template<class Container, class ReturnType = Container::const_pointer>
ReturnType GetBoundedElementPointer(std::map<Key, T>& map, const Key& key) ReturnType GetBoundedElementPointer(Container& container,
const typename Container::key_type& key)
{ {
ReturnType elementPtr {nullptr}; ReturnType elementPtr {nullptr};
// Find the first element greater than the key requested // Find the first element greater than the key requested
auto it = map.upper_bound(key); auto it = container.upper_bound(key);
// An element with a key greater was found // An element with a key greater was found
if (it != map.cend()) if (it != container.cend())
{ {
// Are there elements prior to this element? // Are there elements prior to this element?
if (it != map.cbegin()) if (it != container.cbegin())
{ {
// Get the element immediately preceding, this the element we are // Get the element immediately preceding, this the element we are
// looking for // looking for
@ -32,11 +33,11 @@ ReturnType GetBoundedElementPointer(std::map<Key, T>& map, const Key& key)
elementPtr = &(*it); elementPtr = &(*it);
} }
} }
else if (map.size() > 0) else if (container.size() > 0)
{ {
// An element with a key greater was not found. If it exists, it must be // An element with a key greater was not found. If it exists, it must be
// the last element. // the last element.
elementPtr = &(*map.rbegin()); elementPtr = &(*container.rbegin());
} }
return elementPtr; return elementPtr;
@ -48,8 +49,8 @@ ReturnType GetBoundedElement(std::map<Key, T>& map, const Key& key)
ReturnType element; ReturnType element;
typename std::map<Key, T>::pointer elementPtr = typename std::map<Key, T>::pointer elementPtr =
GetBoundedElementPointer<Key, T, typename std::map<Key, T>::pointer>(map, GetBoundedElementPointer<std::map<Key, T>,
key); typename std::map<Key, T>::pointer>(map, key);
if (elementPtr != nullptr) if (elementPtr != nullptr)
{ {
element = elementPtr->second; element = elementPtr->second;