Added dictionary template class based on GenericArray of KeyValue pairs
This commit is contained in:
68
include/Dictionary.hpp
Normal file
68
include/Dictionary.hpp
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
#include <WString.h>
|
||||||
|
#include "KeyValuePair.hpp"
|
||||||
|
#include "GenericArray.hpp"
|
||||||
|
#include "logger.hpp"
|
||||||
|
|
||||||
|
template <typename K, typename V>
|
||||||
|
class Dictionary : public GenericArray<KeyValuePair<K, V>>
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
void Set(K key, V value)
|
||||||
|
{
|
||||||
|
if (!ContainsKey(key))
|
||||||
|
{
|
||||||
|
this->Append(KeyValuePair<K, V>(key, value));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this->data[IndexOf(key)] = new KeyValuePair<K, V>(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
KeyValuePair<K, V> Get(int index)
|
||||||
|
{
|
||||||
|
if (this->Count() > index)
|
||||||
|
return *this->data[index];
|
||||||
|
return KeyValuePair<K, V>();
|
||||||
|
}
|
||||||
|
|
||||||
|
KeyValuePair<K, V> Get(K key)
|
||||||
|
{
|
||||||
|
int index = this->IndexOf(key);
|
||||||
|
if (index >= 0)
|
||||||
|
return this->Get(index);
|
||||||
|
return KeyValuePair<K, V>();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ContainsKey(K key)
|
||||||
|
{
|
||||||
|
return this->IndexOf(key) >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int IndexOf(K Key)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < this->Count(); i++)
|
||||||
|
{
|
||||||
|
if ((*this->data[i]).GetKey() == Key)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
V &operator[](K key)
|
||||||
|
{
|
||||||
|
int index = this->IndexOf(key);
|
||||||
|
if (index >= 0)
|
||||||
|
{
|
||||||
|
return this->Get(index).GetValue();
|
||||||
|
}
|
||||||
|
return KeyValuePair<K, V>();
|
||||||
|
}
|
||||||
|
|
||||||
|
KeyValuePair<K, V> &operator[](int index)
|
||||||
|
{
|
||||||
|
if (index >= 0)
|
||||||
|
{
|
||||||
|
return this->Get(index).GetValue();
|
||||||
|
}
|
||||||
|
return KeyValuePair<K, V>();
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user