Custom STL Containers

I wrote code that allows you to move the displayed data in the order in which it was entered.

The solution that I encoded a couple of times was:

Given the key type, K and data type D, std :: Map std :: vector

If you want to accidentally find a data record, use map.find(K). When it was necessary to move the card in the input order, use std::vector::iterator (begin(), end()].

It was great, but as an exercise, I wanted to write this 'OrderedMap'as a container compatible with STL. I also have (sharing before this discussion):

template <typename K, typename D>
class OrderedMapValue
{
private:
    K first_ref;
    std::map<K,size_t>& m;
    std::vector<D>& v;
public:
    const K& first
    D& second
    assignment operator=(const D& data) 
    {
        std::map<K,size_t>::const_iterator iter = m.find(first_ref);
        v[iter.second] = data;  // error checking of iter stripped
    }
};

Next, assuming

template <typename K, typename D>
class OrderedMap
{
public:
     typename OrderedMapValue<K,D>& OrderedMap<K,D>::operator[](const K&);
     // snip...
};

class MyClass
{
public:
    MyClass(std::string s) : _my_data(s) {}
private:
    std::string _my_data;
};

The following code works:

OrderedMap<std::string,MyClass*> omap;
omap["MyKey"] = new MyClass("dummy");

However, this code does not:

OrderedMap::iterator iter = omap.find("MyKey");
MyClass * obj = iter->second;
delete obj;
iter->second = new MyClass("dummy");

Assuming I did something a) Structurally stupid or b) Without too much difficulty, how should this be done?

, , , , , , STL, .

,

+3
2

, , , , , :

template <typename K, typename D>
class OrderedMap
{
private:
        std::map<K,size_t> &m;
        std::vector<D> &v;
public:
    typename pair<K,D> TYPE;

        TYPE& operator[](const K &k)
    {
        return v[ m[ k ]];
    }

    TYPE& operator[](size_t idx)
    {
        return v[ idx ];
    }

    pair<iterator,bool> insert( const TYPE& pair )
    {
        map<K, size_t>::const_iterator iter;
        iter = m.find( pair.first );

        if( iter != m.end() )
            return make_pair( v[ iter.second], false );

        m.insert( make_pair( pair->first, v.size() ));
        v.push_back( pair->second );

        return make_pair(  v.last() , inserted );
    }

    iterator &begin()
    {
        return v.begin();
    }
    // etc
};
+2

OrderedMapValue::operator= :

    std::map<K,size_t>::const_iterator iter = m.find(first_ref);

first_ref? ( ) . , , .

const K& first.

?

: , first_ref ; , , m.find(first_ref) , OrderedMapValue.

0

Source: https://habr.com/ru/post/1705040/


All Articles