c++ map array operator overloading enable setting value to

198 views Asked by At

i try to do ordered map ( simple very simple ) i want to overload the map "[] = value " operator . that is the equal sign that come after the array operator but how ? i have this :

template <typename  K, class V>
class OrderedMap
{
    public:
        OrderedMap(){};
        ~OrderedMap(){};
        void setValue(K _k);
        void operator[] (K _k);
    private:
        std::vector<K> insertOrder;
        std::tr1::unordered_map<K, V> myTable;
};

template <typename  K, class V>
OrderedMap<K, V>::setValue(K _k)
{
    myTable[_k];
    insertOrder.push_back(_k);
}

template <typename  K, class V>
void OrderedMap<K, V>::operator[] (K _k) 
{
     ......
}

i have the array set and working but how to add the option to add value to key via array operator so this will be vaild

m_Map[CONST1] = "value"
2

There are 2 answers

4
Daniel On BEST ANSWER

Basically operator[] is a function call which only supplies the parameters inside of the brackets to your class.

So in C++ you actually use the operator[] a bit different than let's say Delphi or C#: The operator[] usually returns a reference to the item inside the collection:

myContainer[3] = value;

will actually resolve to the following:

MyItem refToObj& = myContainer[3];
refToObj = value;

the operator[] should then have the following form

MyItem& MyContainer::operator[](int);

If you cannot work with references for some reason (for example you don't actually HAVE a MyItem instance inside your container and the operator[] should convert the object into a different type) then the only approach is to use a "helper object":

MyContainer::Helper helper = myContainer[3];
helper = value;

the operator[] should then have the following form

MyContainer::Helper MyContainer::operator[](int);

where MyHelper is a special class which overloads the operator= which then does the container specific conversion (see vector<bool> if you're interested in this approach).

Edit: To come back to the problem: I'm a bit unsure what you exactly want to accomplish, but I think you'd need to use the "Helper" approach:

class OrderedMap
{
    class ItemHelper
    {
    public:
        ItemHelper(OrderedMap& map, K key): m_map(map), m_key(key) {}

        //writing a value
        V& operator=(const V& v)
        {
            m_map.setValue(m_key);
            m_map.myTable[m_key] = v;
        }

        //reading a value
        operator const V&() { return m_map[k]; }
    private:
        K m_key;
        OrderedMap& m_map;
    };
};
0
TartanLlama On

Your operator[] needs to return a non-const reference to the indexed element:

V& OrderedMap<K, V>::operator[] (K _k)

In your function body, you need to check if that key is already represented in the map and, if so, return a reference to the corresponding value. If that key is not in the map, default construct a V, add it to the map, then return a reference to the value in the map.