C++ map having key as a user define data type

C++ map stores keys in ordered form (Note that it internally use a self balancing binary search tree). Ordering is internally done using operator ” < " So if we use our own data type as key, we must overload this operator for our data type.

Let us consider a map having key data type as a structure and mapped value as integer.

// key's structure
struct key
{
int a;
};

filter_none

editclose

play_arrow

linkbrightness_4code

// CPP program to demonstrate how a map can

// be used to have a user defined data type

// as key.

#include <bits/stdc++.h>

usingnamespacestd;

structTest {

intid;

};

// We compare Test objects by their ids.

booloperator<(constTest& t1, constTest& t2)

{

return(t1.id < t2.id);

}

// Driver code

intmain()

{

Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };

// Inserting above four objects in an empty map

map<Test, int> mp;

mp[t1] = 1;

mp[t2] = 2;

mp[t3] = 3;

mp[t4] = 4;

// Printing Test objects in sorted order

for(autox : mp)

cout << x.first.id << " "<< x.second << endl;

return0;

}

chevron_right

filter_none

Output:

101 3
102 2
110 1
115 4

We can also make < operator a member of structure/class.

filter_none

editclose

play_arrow

linkbrightness_4code

// With < operator defined as member method.

#include <bits/stdc++.h>

usingnamespacestd;

structTest {

intid;

// We compare Test objects by their ids.

booloperator<(constTest& t) const

{

return(this->id < t.id);

}

};

// Driver code

intmain()

{

Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };

// Inserting above four objects in an empty map

map<Test, int> mp;

mp[t1] = 1;

mp[t2] = 2;

mp[t3] = 3;

mp[t4] = 4;

// Printing Test objects in sorted order

for(autox : mp)

cout << x.first.id << " "<< x.second << endl;

return0;

}

chevron_right

filter_none

Output:

101 3
102 2
110 1
115 4

What happens if we do not overload < operator?
We get compiler error if we try to insert anything into the map.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.