I want to create a map that will contain composite key. For example I have student's roll no and semester in which he/she is studying. Now I want to create a map such that roll no and semester together act as the key for the map.
EDIT: A moment's doubt caused me to wonder whether an operator==()
must also be supplied by a key type, since obviously when looking up values in a map
, tests for equality must be used under the hood. But 23.1.2/3 in the 2003 C++ standard says it's not necessary: equality between two key objects a
and b
is required to be determined by checking whether both a < b
and b < a
are false. :)
#include <map>
struct key {
int rollNo;
int semester;
string whateverElse;
// Provide a "<" operator that orders keys.
// The way it orders them doesn't matter, all that matters is that
// it orders them consistently.
bool operator<(key const& other) const {
if (rollNo < other.rollNo) return true; else
if (rollNo == other.rollNo) {
if (semester < other.semester) return true; else
if (semester == other.semester) {
if (whateverElse < other.whateverElse) return true;
}
}
return false;
}
};
std::map<key, whateverValueTypeYouWant> dictionary;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With