映射定义中的 Cref 后递增

Cref postincrementation in Map definition

本文关键字:Cref 定义 映射      更新时间:2023-10-16

所以我在向量上的映射类上有这样的定义,除了后增量之外,它工作得很好,它不能正常工作。您可以在示例中看到变量 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;
}

是的,我已经修复了这个问题,++ 运算符的重载应该看起来像这样:

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

这可以解决所有问题。