开发者

Is it a good idea to index an STL map with a pair?

开发者 https://www.devze.com 2022-12-27 17:09 出处:网络
I\'m just wondering if it is a good idea to make a data structure like std::map< std::pair<int,int>,std开发者_如何学编程::string >

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!


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.


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.


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>.

0

精彩评论

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