Md Fahad
Md Fahad

Reputation: 25

Is there a default C++ comparator for user defined structure?

#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
    map<TreeNode*,int> mp;
    TreeNode* x=new TreeNode(4);
    TreeNode* y=new TreeNode(5);
    TreeNode* z=new TreeNode(6);
    mp[x]=1;
    mp[y]=2;
    mp[z]=3;

    cout<<mp[x]<<endl;

    return 0;
}

The above code compiles and gives the desired outut but why don't we need to define a custom comparator to create the map mp; Does C++ does it itself? Same with unordered_map the code works fine.

Upvotes: 0

Views: 365

Answers (2)

eerorika
eerorika

Reputation: 238311

Is there a default C++ comparator for user defined structure?

Not implicitly and not until C++20.

Since C++20, it is possible to define default comparison operators like this:

struct T {
    auto operator<=>(const T&) const = default;
};

why don't we need to define a custom comparator to create the map mp;

The keys of the map are pointers. Pointers are not user defined types, and they are comparable.

Upvotes: 3

NathanOliver
NathanOliver

Reputation: 180500

You have a map of TreeNode*, not TreeNode. A TreeNode* is just a pointer and like all other non-class member pointers, the default comparator for std::map, std::less, will handle them in a implementation defined manner.

If you had a map<TreeNode,int> mp;, then it would fail to compile as there is no operator < defined for TreeNode.

Upvotes: 5

Related Questions