开发者

c++: How to transform a map iterator which point to pair into a "regular" pair pointer

those are the maps:

multimap<SortKey,T> firstMap;
multimap<SearchKey,pair<SortKey,T>*> secondMap;


template <class T,class SortKey, class SearchKey> bool GarageDataBase<T,SortKey,SearchKey>::Add(T data,SortKey key1, SearchKey key2) 
{
 multimap<SortKey,T>::iterator it;
 it=(firstMap.insert(pair<SortKey,T>(key1,data)));
 pair<SortKey,T> *mizi=&*it;

 secondMap.insert(pair<SearchKey,pair<SortKey,T>*>(key2,mizi));
 return true;
}

I am trying to insert a pair into the firstMap and get a pointer to this 开发者_StackOverflow社区pair and insert it into the "second" field in the secondMap

so that i could go into my firstMap from the secondmap.

pair<SortKey,T> *mizi=&*it;

this doesn't compile saying :

error C2440: 'initializing' : cannot convert from 'std::pair<_Ty1,_Ty2> *' to 'std::pair<_Ty1,_Ty2> *'

any idea whats going on or maybe a better way to make it work?


pair<SortKey,T> is not the same as multimap<SortKey,T>::value_type. The latter is pair<const SortKey,T> since the key is not supposed to change. And since pair<SortKey,T> and pair<const SortKey,T> are not reference-related but two distinct types, the compiler doesn't accept the code. If you account for the const key it should work.


pair<const SortKey,T> *mizi=new pair<const SortKey,T>;
    it=(firstMap.insert(pair<SortKey,T>(key1,data)));
    mizi=&*it;

    secondMap.insert(pair<SearchKey,pair<const SortKey,T>*>(key2,mizi));
    return true;

Ok after changing it to const in insert and in the multimap it seems to work


It would be easier to use:

multimap<SortKey,T> firstMap;
multimap<SearchKey,firstMap::iterator> secondMap;


template <class T,class SortKey, class SearchKey> 
bool GarageDataBase<T,SortKey,SearchKey>::Add(T data,SortKey key1, SearchKey key2) 
{
   firstMap::iterator it;
             =firstMap.insert(firstMap::value_type(key1,data));
   secondMap.insert(secondMap::value_type(key2,it));
   return true;
}

This has several advantages: 1. don't have to know internal representation of multimap's types 2. Cannot do something stupid like incrementing the pointers but otherwise syntax is the same SortKey sortkey=secondMap.find(searchkey)->second->first;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜