Creating a C ++ map from a composite key

I want to create a map that will contain a composite key. For example, I do not have a student and a semester in which he studies. Now I want to create such a card that roll no and semester together become the key for the card.

+7
source share
4 answers

Instead of defining your own class for the key and defining your own comparison operators, since you care about the roll number and semester, I would use std :: pair.

#include <utility> #include <map> // This maps an std::pair of (roll number, semester) to a StudentRecord. std::map<std::pair<int, int>, StudentRecord> studentMap; studentMap.insert(std::pair<std::pair<int, int>, StudentRecord>(std::make_pair(100, 100), StudentRecord()); 

If you use something other than int for the number and semester, you can easily use the ones that are paired. Just keep in mind that if you use custom structures for these objects, they will need to implement equality and comparison operators, in which case you will lose the advantage of using a pair, instead of directly using any other structure.

+10
source

EDIT: Some doubt made me wonder if operator==() should be a type key, since, obviously, when searching for values ​​in map , tests for equality should be used under the hood. But 23.1.2 / 3 in the C ++ 2003 standard says that this is not necessary: ​​you need to determine the equality between the two key objects a and b , checking if both a < b and b < a 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; 
+8
source
Keys

std :: map must implement the <operator to search and enter keys. Example:

 #include <map> struct Student { Student(int roll_no, int semestre) : roll_no(roll_no), semestre(semestre) {} int roll_no; int semestre; bool operator< (Student const &s) const { return semestre* 100000+ roll_no< s.semestre* 100000+ s.roll_no; } }; #include <iostream> #include <ostream> int main() { std::map<Student, int> m; m[Student(1, 1)]= 42; m[Student(1, 2)]= 43; std::cout<< m[Student(1, 1)]; } 
+1
source

You can define the type of structure containing the member roll_no and semester.

  struct stu_key { int roll_no; int semester; bool operator <(const stu_key &sk) const { //compare roll_no and semester } }; std::map<stu_key , value_type> stu_map; 
+1
source

All Articles