Totte Karlsson
Totte Karlsson

Reputation: 1341

How to return a std::map item

I have an issue on returning an item from a std::map residing inside a class. I am trying to create a simple function like

ExplorerObjectMapItem* MyClass::getFirst()
{
    mInternalMapIterator = mObserverLookup.begin();
    ExplorerObjectMapItem* item = &*mInternalMapIterator;
    return item;
}

where the following typedefs are used

typedef map< Subject*, shared_ptr<ExplorerObject> > ExplorerObjectMap;
typedef pair<Subject*, shared_ptr<ExplorerObject> > ExplorerObjectMapItem;
typedef ExplorerObjectMap::iterator                 ExplorerObjectIter;

and the map and iterator are class members:

ExplorerObjectMap                               mObserverLookup;
ExplorerObjectIter                              mInternalMapIterator;

The above code for the getFirst() function gives a compile error saying

E2034 Cannot convert 'pair<Subject * const,boost::shared_ptr<ExplorerObject>
 > *' to 'ExplorerObjectMapItem *'

Not sure what is going on here. Any help appreciated.

Upvotes: 0

Views: 578

Answers (1)

aschepler
aschepler

Reputation: 72271

A std::map<K,V> does not contain std::pair<K,V> objects. It contains std::pair<const K, V> objects. That missing const is what throws off the conversion.

You could fix this with either

typedef pair<Subject* const, shared_ptr<ExplorerObject> > ExplorerObjectMapItem;

or

typedef ExplorerObjectMap::value_type ExplorerObjectMapItem;

Upvotes: 2

Related Questions