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;
};
#include <bits/stdc++.h>
using namespace std;
struct Test {
int id;
};
bool operator<( const Test& t1, const Test& t2)
{
return (t1.id < t2.id);
}
int main()
{
Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };
map<Test, int > mp;
mp[t1] = 1;
mp[t2] = 2;
mp[t3] = 3;
mp[t4] = 4;
for ( auto x : mp)
cout << x.first.id << " " << x.second << endl;
return 0;
}
|
Output:
101 3
102 2
110 1
115 4
We can also make < operator a member of structure/class.
#include <bits/stdc++.h>
using namespace std;
struct Test {
int id;
bool operator<( const Test& t) const
{
return ( this ->id < t.id);
}
};
int main()
{
Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };
map<Test, int > mp;
mp[t1] = 1;
mp[t2] = 2;
mp[t3] = 3;
mp[t4] = 4;
for ( auto x : mp)
cout << x.first.id << " " << x.second << endl;
return 0;
}
|
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.
#include <bits/stdc++.h>
using namespace std;
struct Test {
int id;
};
int main()
{
map<Test, int > mp;
Test t1 = {10};
mp[t1] = 10;
return 0;
}
|
Output:
/usr/include/c++/5/bits/stl_function.h:387:20: error: no match for 'operator<' (operand types are 'const Test' and 'const Test')
{ return __x < __y; }
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!