地图定义中的Cref postincrementation

时间:2014-02-24 18:05:54

标签: c++ map

所以我对vector上的map类有这样的定义,除了后增量之外它工作得很好,后者不能正常工作。您可以在示例中看到变量a应该等于10(在赋值后增加后)。但它等于11.我不知道如何解决这个问题。

#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;
}

1 个答案:

答案 0 :(得分:0)

是的,我已经修复过,++运算符的重载应该是这样的:

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

这可以解决所有问题。