C++ map having key as a user define data type
Last Updated :
30 Mar, 2018
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; }
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...