56 lines
1.6 KiB
C++
56 lines
1.6 KiB
C++
#include <algorithm>
|
|
#include <iostream>
|
|
#include <type_traits>
|
|
#include <vector>
|
|
|
|
template <typename Key, typename Value>
|
|
class VectorMap {
|
|
std::vector<Key> keys_;
|
|
std::vector<Value> values_;
|
|
|
|
static_assert(std::is_default_constructible<Value>::value, "Value should have the default constructor");
|
|
static_assert(std::is_default_constructible_v<Value>, "Value should have the default constructor");
|
|
|
|
public:
|
|
using K = Key;
|
|
using V = Value;
|
|
void insert(const Key& k, const Value& v) {
|
|
keys_.emplace_back(k);
|
|
values_.emplace_back(v);
|
|
}
|
|
|
|
static constexpr bool isIntKey() {
|
|
// if (std::is_integral_v<Key>) {
|
|
if (std::is_same_v<Key, int>) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
Value& operator[](const Key& k);
|
|
Value& at(const Key& k);
|
|
|
|
static constexpr bool is_int_key = std::is_same_v<Key, int>;
|
|
};
|
|
|
|
template <typename Key, typename Value>
|
|
Value& VectorMap<Key, Value>::operator[](const Key& k) {
|
|
auto it = std::find(std::begin(keys_), std::end(keys_), k);
|
|
if (it == std::end(keys_)) {
|
|
keys_.emplace_back(k);
|
|
values_.emplace_back(Value{});
|
|
return values_.back();
|
|
}
|
|
auto dist = std::distance(keys_.begin(), it);
|
|
return values_[dist];
|
|
}
|
|
|
|
template <typename Key, typename Value>
|
|
Value& VectorMap<Key, Value>::at(const Key& k) {
|
|
auto it = std::find(std::begin(keys_), std::end(keys_), k);
|
|
if (it == std::end(keys_)) {
|
|
throw std::out_of_range("This key does not exist");
|
|
}
|
|
auto dist = std::distance(keys_.begin(), it);
|
|
return values_[dist];
|
|
}
|