[Qt-interest] "Double Sided Map"?

Sean Harmer sean.harmer at maps-technology.com
Wed Feb 10 01:19:47 CET 2010


Hi,

Jefferson Bandeira wrote:
> Hello guys, i hope you can answer my question.
> Actually in my application I need to map some values to Strings, 
> however, I also need to make a "reverse mapping", i mean, i want to be 
> able to see which QString is mapped to the number 3, but i also need to 
> know which Number the QString "three" is mapped to.
> At the moment i'm doing something like this :
> ----------------------------------------------
> QMap<int, QString> i2string;
> QMap<QString, int> string2i;
> i2string[3] = QString("three");
> string2i["three"] = 3;
> ----------------------------------------------
> This indeed works for what i need, however, that's a bit messy, since 
> any changes i make to one of the maps i must do to the other and this is 
> kinda dangerous, since someone can easily forget about this, or the maps 
> can be Desynched.
> So, My question is :
> Is there any Structure i can use in which i can insert the pair of 
> things once, and i can query the structure to give me what i want, both 
> ways?
> Something like :
> MagicStructure<int, QString> struct;
> struct.insert(3, QString("three"));
> struct.get(3); // Returns "three"
> struct.get("three"); // Returns 3
> PS : I can ensure that both values are unique through all structure, so 
> that won't be a problem.
> Regards,
> Jefferson Bandeira

I do not know of anything ready made but it should be trivial to wrap a 
forward map and a reverse map into a custom class and simply provide 
forwarding functions as needed.

For e.g.

class TwoWayMap
{
public:
     TwoWayMap()
     : m_forwardMap(), m_reverseMap()
     {
     }

     void insert( const QString& str, int i )
     {
         m_forwardMap.insert( i, str );
         m_reverseMap.insert( str, i );
     }

     ...more api as needed for lookups etc...

private:
     QMap<int, QString> m_forwardMap;
     QMap<QString, int> m_reverseMap;
};

ATB,

Sean



More information about the Qt-interest-old mailing list