Is it good to index an STL map with a pair?
The pairs will be ordered using a pair operator<
(the default comparison 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 can be confusing to use a pair as a map key, especially when dealing with map iterators (it it->first.first
just looks ridiculous to get the first element of a key pair). But in some cases it can be easier than creating a whole new structure for the key.
As with all things, use with caution, and if it's not straightforward and easy to understand, it's probably best to find another way to do it.
a source to share
You can. In my opinion, though, you should do something more expressive because it was std::pair
n't meant to be. 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>
instead map<pair<int,int>,string>
.
a source to share
If you want to have two indexes on your hash table, you should look at Boost :: multiindex containers.
As for answering your question, why not if you can handle the constraints others have pointed out. I am always for any solution that is clear, easy to use, and consistent with the purpose of the given problem.
a source to share