I have a class called Dictionary that contains a key-value pair, a pointer to this key-value pair, and an int that holds the size of the dictionary.
template<typename K, typename V>
class Dictionary
{
public:
V& operator[](K key);
private:
struct KeyValue
{
K key;
V value;
}; //the key-value pair struct
KeyValue* array; //pointer to an array of items (the key-value pairs)
int size; //size of the dictionary (i.e. the array size)
};
I am trying to overload the [] operator for this class and when I do so, I get a segmentation fault error
template<typename K, typename V>
V& Dictionary<K,V>::operator[](K key){
for (size_t i = 0; i < size; i++) {
if (key == array[i].key) {
return array[i].value;
}
}
array[size].value = 0;
size++;
return array[size-1].value;
}
I beleive that the seg fault is occuring in this line
array[size].value = 0;
However, I don't know exactly why it's happening. Any help is greatly appreciated. Thanks!
std::map?