I need to use an unordered_multimap for my Note objects and the keys will be the measureNumber member of my objects. I’m trying to implement it as shown here but I’m stuck.
First off, I don’t understand why I have to overwrite the operator== before I can use it. I’m also confused about why I need a hash and how to implement it. In this example here, none of those two things is done.
So based on the first example, this is what I have:
class Note {
private:
int measureNumber;
public:
inline bool operator== (const Note ¬eOne, const Note ¬eTwo);
}
inline bool Note::operator ==(const Note& noteOne, const Note& noteTwo){
return noteOne.measureNumber == noteTwo.measureNumber;
}
I don’t know how to implement the hash part though. Any ideas?
std::multimapis based on a sorted binary tree, which uses a less-than operation to sort the nodes.std::unordered_multimapis based on a hash table, which uses hash and equality operations to organize the nodes without sorting them.The sorting or hashing is based on the key values. If the objects are the keys, then you need to define these operations. If the keys are of predefined type like
intorstring, then you don’t need to worry about it.The problem with your pseudocode is that
measureNumberis private, so the user ofNotecannot easily specify the key to the map. I would recommend makingmeasureNumberpublic or rethinking the design. (Is measure number really a good key value? I’m guessing this is musical notation.)The objects can be keys and values at the same time, if you use
std::multisetorstd::unordered_multiset, in which case you would want to define the operator overload (and possibly hash). Ifoperator==(oroperator<) is a member function, then the left-hand side becomesthisand the right-hand side becomes the sole argument. Usually these functions should be non-member friends. So then you would haveThis class could be used with
std::multiset. To perform a basic lookup, you can construct a dummy object with uninitialized values except formeasureNumber— this only works for simple object types.