ArepitaDePernil's blog

By ArepitaDePernil, history, 5 months ago, In English,

Hello , lets say I want to overload a SET so when I use set.count() or set.find() it follows some rules, for example given a set of pairs:

{1,2} {3,4} {1,4} ...

If it says pair A and B are equivalent if A.y < B.x or A.x > B.y , how could I overload such a function? since I tried using "==" and "<" with no success :(

 
 
 
 
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
5 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by ArepitaDePernil (previous revision, new revision, compare).

»
5 months ago, # |
  Vote: I like it 0 Vote: I do not like it

You can alwsys use inheritance...

»
5 months ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

Just like any other user-defined function, but you should use the operator keyword as shown in the following example.

#include <bits/stdc++.h>

using namespace std;

using pair_t = pair<int,int>;

inline istream& operator >> (istream& in, pair_t& x)
{
    return in >> x.first >> x.second;
}

inline bool operator < (const pair_t& x, const pair_t& y)
{
    return (x.first != y.first) ? (x.first < y.first) : (x.second < y.second);
}

inline ostream& operator << (ostream& out, const pair_t& x)
{
    return out << '{' << x.first << ',' << x.second << '}';
}

int main()
{
    ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);

    pair_t a, b; 
    
    cin >> a >> b, cout << a << " < " << b << " = " << boolalpha << (a < b);
}
Input:
4 2 3 4

Output:
{4,2} < {3,4} = false
=====
Used: 30 ms, 0 KB