Yoav Linder
Yoav Linder

Reputation: 123

Creating a []= operator for a dictionary cpp

i am trying to be able to decleare a dictionary and be able to do this:

Dict d;
d.set("Home",34);
d["Home"] =56;

but i keep getting errors (i cant understand the lvalue and the rvalue thing). but i keep getting errors that i can not do the "d["House"] = 56" line because of an lvalue problem. i have tried to override the operator '=' also but it did not work for me.

this is my class header file:

#include <iostream>
#include <vector>
using namespace std;

template <class K, class V>
class Dict {
protected:
    vector<K> keys;
    vector<V> values;
    K Key;
    V Value;
public:
    Dict();
    Dict(K Key, V Value);
    void set(K Key, V Value);
    void print();
    V operator[](K* str);
    const V& operator[](K &str);
    Dict<K,V>& operator==(const Dict<K,V> dict);
};
template class Dict<string, int>;

this is my cpp file:

#include "Dict.h"
template <class K, class V>
Dict<K,V>::Dict() {};

template <class K, class V>
Dict<K,V>::Dict(K Key, V Value) :
        Key(Key), Value(Value){};

template <typename K, typename  V>
void Dict<K,V>::set(K Key, V Value) {
    keys.push_back(Key);
    values.push_back(Value);
}


template <typename K, typename  V>
void Dict<K,V>::print() {
    cout << "{";
    for(int i = 0; i < this->keys.size(); i++){
        cout << "'" << this->keys[i] << "'" << "," << this->values[i];
        if(i == this->keys.size() - 1){
            cout << "}";
        }
        else{
            cout << " ,";
        }
    }
}


template <typename K, typename  V>
V Dict<K,V>::operator[](K* str) {
    V lol;
    for(int i = 0; i < this->keys.size(); i++){
        if(this->keys[i] == *str){
            return this->values[i];
        }
    }
    return lol;
}

template <typename K, typename  V>
<K,V>& Dict<K,V>::operator==(const Dict<K, V> dict) {
    *this = dict;
    return *this;
}

template <typename K, typename  V>
const V& Dict<K,V>::operator[](K &str) {
    V lol;
    for(int i = 0; i < this->keys.size(); i++){
        if(this->keys[i] == str){
            return this->values[i];
        }
    }
    return lol;
}

and this is my main:

#include "Dict.h"

int main() {
    Dict<string, int> d,t;
    d.set("Home",34);
    d.set("c",13);
    d.set("House",8);

    string str = "HOuse";
    string *str2 = &str;
    int i = d[str2];

    d[str2] == 56;
    d.print();

    return 0;
}

Upvotes: 0

Views: 495

Answers (1)

Tyker
Tyker

Reputation: 3047

instead of this

V operator[](K* str);

you should have

V& operator[](K* str);
const V& operator[](K* str) const;

your operator is returning by value so what he is returning is a temporary copy so modification will be applied on that copy

and the second operator to allowed read on a constant object of your class

Upvotes: 5

Related Questions