Question

So I have such definition on map class on vector, it works good except for post-incrementation, which doesn't work as it should. You can see in example that variable a should be equal to 10 (post-incremented after assignment). But it's equal to 11. I have no idea how to fix that.

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

template<class T>
class Map {
    class Cref {
        friend class Map;
        Map& m;
        string key;
        T value;
    public:
        operator double() {
            return m.read(key);
        };

        Map::Cref & operator=(double num) {
            m.write(key, num);
            return *this;
        };

        Map::Cref & operator++(int) {
            Cref c(*this);

            m.increment(key, value);

            return c;
        }

        Cref(Map& m, string a)
            : m(m),
             key(a) {};
    };

public:
    class Unitialized {};
    struct Record {
        string key;
        T value;
    };

    vector<Record> data;
    Map() {}
    ~Map() {}

    bool ifexist(string k) {
        for (int i = 0; i < data.size(); i++) {
            if (data.at(i).key == k)
                return 1;
        }
        return 0;
    }

    Cref operator[](string key) {
        return Map::Cref( * this, key);
    }

private:
    void increment(string key, T value) {
       if (ifexist(key) == 0) {
            throw Unitialized();
        }
        for (int i = 0; i < data.size(); i++) {
            if (data.at(i).key == key)
                data.at(i).value += 1;
        }
    }
    void write(string key, T value) {
        if (ifexist(key) == 1) {
            cout << "Element already exist" << endl;
            return;
        }
        Record r;
        r.key = key;
        r.value = value;
        data.push_back(r);
    }

    double read(string key) {
        if (ifexist(key) == 0) {
            throw Unitialized();
        }
        for (int i = 0; i < data.size(); i++) {
            if (data.at(i).key == key)
                return data.at(i).value;
        }
        return 0;
    }
};

int main(int argc, char** argv) {
    Map<int> m;
    m["ala"] = 10;
    int a = 0;
    a = m["ala"]++;
    cout << a << endl;

    try {
        cout << m["ala"] << endl;
        cout << m["ola"] << endl;
    } catch (Map<int>::Unitialized&) {
        cout << "Unitialized element" << endl;
    }

    return 0;
}
Was it helpful?

Solution

Yes, I already fixed that, overloading of ++ operator should look like that :

T operator ++(int)
    {
        T ret = m.read(this->key);
        m.increment(key, value);
        return ret;
    }

This fixes everything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top