lundi 9 mars 2015

std::map: Use only part of keytype for comparison

I have a map that uses pairs of some datatype KT as keys to map to a matrix type, i.e. sth. like



std::map<std::pair<KT,KT>, MatType, PairCompare>


For comparison I only need the first element of the pair, so PairCompare is very simple



struct PairCompare
{
bool operator()(const std::pair<KT,KT>& lhs,const std::pair<KT,KT>& rhs) const
{return lhs.first<rhs.first;}
};


I would however like to use the whole pair as a key, as I constantly need the second element in operations while iterating through the map.


Sometimes, I also need to find a map entry based on a single KT only. Of course I should use a pair of KT in the find() routine, but I would like to avoid creating a dummy pair of KT, as I have to do this many times and that could get expensive. I would like to use something like



std::map<std::pair<KT,KT>, MatType, PairCompare> mymap;
KT mykey = // ... some implementation of KT;

// fill map

auto it = mymap.find(mykey); // <- will not work of course, but what I would like to use
auto it = mymap.find(std::pair<KT,KT>(mykey,mykey)); // <- what I am using so far (creating a dummy pair)


Mykey can in general be both lvalue and rvalue (in my application).


Is there any way of defining a different type of key that contains two KT instances and only uses one for map ordering and also enables finding by single KTs that works straight forward? Can it be done with some special comparison object? Maybe there is also a smart way of getting around using pairs of KT as Key at all, but still enabling access to the second KT in map iterations?


Thanks for your help!


P.S.: to be precise, as KT I am using



typedef std::vector<int> KT

Aucun commentaire:

Enregistrer un commentaire