Skip to content
Related Articles

Related Articles

C++ map having key as a user define data type
  • Difficulty Level : Medium
  • 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;
};




// CPP program to demonstrate how a map can
// be used to have a user defined data type
// as key.
#include <bits/stdc++.h>
using namespace std;
struct Test {
    int id;
};
  
// We compare Test objects by their ids.
bool operator<(const Test& t1, const Test& t2)
{
    return (t1.id < t2.id);
}
  
// Driver code
int main()
{
    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 (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.




// With < operator defined as member method.
#include <bits/stdc++.h>
using namespace std;
struct Test {
    int id;
  
    // We compare Test objects by their ids.
    bool operator<(const Test& t) const
    {
        return (this->id < t.id);
    }
};
  
// Driver code
int main()
{
    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 (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;
};
  
// Driver code
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; }
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :