Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating C++ map from composite key

Tags:

c++

map

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.

like image 258
Sudip Avatar asked Oct 18 '12 06:10

Sudip


1 Answers

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;
like image 193
j_random_hacker Avatar answered Sep 28 '22 00:09

j_random_hacker