tags:

views:

89

answers:

3

Hi Everyone,

I'm just wondering if it is a good idea to make a data structure like

std::map< std::pair<int,int>,std::string >

Just wondering how the pairs would be ordered internally... :S

Thanks!

A: 

You can. In my opinion though you should do something more expressive than that, because std::pair wasn't meant for this. For example, if you want to store strings in a map by their hash then you can do something like:

struct Hash {
    int hash_low;
    int hash_high;

    bool operator<(const Hash& other) const;
};

And then use map<Hash,string> rather than map<pair<int,int>,string>.

wilhelmtell
Perhaps a simple "typedef pair<int,int> Hash" would be sufficient? I can't imagine that the pair class is significantly less efficient than a struct...
Jeremy Friesner
It's not efficiency, it's expressiveness. Whatever works for you: a `typedef`, a `struct`, whatever. You use things like `pair` when you're writing a library, not concrete, single-purpose code.
wilhelmtell
+4  A: 

The pairs would be ordered using the pair operator< (the default compare operation for std::map), which

Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second)

(C++03, 20.2.2/6)

Note that it could get confusing using a pair as a map key, especially when working with map iterators (it->first.first to get the first element of the key pair just looks ridiculous). But in some cases it might be easier than creating a whole new struct for the key.

As with all things, use with care, and if it's not straightforward and easy to understand, it's probably better to find a different way to do it.

James McNellis
thanks for your response!
jm1234567890
+1  A: 

If you're looking to have two indexes for your hash table then you should look at Boost::multiindex containers.

As far as answering your question, why not if you can deal with the limitations others have pointed out. I'm always for any solution that is clear, easy to use, and suits the purposes of the problem at hand.

wheaties