Some improvements to VectorMap interface. Added moving operator[], contains and [[nodiscard]] to find().

This commit is contained in:
Patrick 2025-03-28 11:43:32 +01:00
parent 91d53805b5
commit e35f5a35f8

View File

@ -4,6 +4,7 @@
#if !defined(MIJIN_CONTAINER_VECTOR_MAP_HPP_INCLUDED) #if !defined(MIJIN_CONTAINER_VECTOR_MAP_HPP_INCLUDED)
#define MIJIN_CONTAINER_VECTOR_MAP_HPP_INCLUDED 1 #define MIJIN_CONTAINER_VECTOR_MAP_HPP_INCLUDED 1
#include <algorithm>
#include <stdexcept> #include <stdexcept>
#include <vector> #include <vector>
#include "./boxed_object.hpp" #include "./boxed_object.hpp"
@ -140,6 +141,16 @@ public:
{ {
return at(key); return at(key);
} }
TValue& operator[](TKey&& key)
{
auto it = find(key);
if (it != end())
{
return it->second;
}
return emplace(std::move(key), TValue()).first->second;
}
[[nodiscard]] [[nodiscard]]
iterator begin() MIJIN_NOEXCEPT { return {keys_.data(), values_.data()}; } iterator begin() MIJIN_NOEXCEPT { return {keys_.data(), values_.data()}; }
@ -234,6 +245,7 @@ public:
return eraseImpl(idx, count); return eraseImpl(idx, count);
} }
[[nodiscard]]
iterator find(const TKey& key) MIJIN_NOEXCEPT iterator find(const TKey& key) MIJIN_NOEXCEPT
{ {
for (std::size_t idx = 0; idx < keys_.size(); ++idx) for (std::size_t idx = 0; idx < keys_.size(); ++idx)
@ -246,6 +258,7 @@ public:
return end(); return end();
} }
[[nodiscard]]
const_iterator find(const TKey& key) const MIJIN_NOEXCEPT const_iterator find(const TKey& key) const MIJIN_NOEXCEPT
{ {
for (std::size_t idx = 0; idx < keys_.size(); ++idx) for (std::size_t idx = 0; idx < keys_.size(); ++idx)
@ -257,6 +270,12 @@ public:
} }
return end(); return end();
} }
[[nodiscard]]
bool contains(const TKey& key) const MIJIN_NOEXCEPT
{
return std::ranges::contains(keys_, key);
}
private: private:
iterator eraseImpl(std::ptrdiff_t idx, std::ptrdiff_t count = 1) MIJIN_NOEXCEPT iterator eraseImpl(std::ptrdiff_t idx, std::ptrdiff_t count = 1) MIJIN_NOEXCEPT
{ {