in the question sort game? why operator overloading is being used. Cant we do it without it, by simply writing a<b;
In the question sort game?
hi @mehulbhandari358 where is operator overloading used? Please share the code if you are talking about some particular approach
it is used in the editors code
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Employee
{
public:
int salary;
string name;
Employee( int sal , string nam)
{
salary = sal;
name = nam;
}
};
bool operator>( string s1 , string s2 )
{
int min = s1.size() < s2.size() ? s1.size() : s2.size();
int index = 0;
while( index < min && s1[index] == s2[index])
{
index++;
}
if( index >= min )
{
if( s1.size() > s2.size() ) return true;
else return false;
}
if( s1[index] > s2[index] ) return true;
else return false;
}
bool lol( Employee e1 , Employee e2 )
{
if( e1.salary > e2.salary )
{
return true;
}
else
if( e1.salary < e2.salary )
{
return false;
}
return e2.name > e1.name;
}
void sort2( vector<Employee> &v )
{
sort( v.begin() , v.end() , lol);
}
int main()
{
int n2;
cin >> n2;
int n;
cin >> n;
vector<Employee> v;
for(int i = 0 ; i < n ; i++ )
{
string s;
cin >> s;
int n;
cin >> n;
Employee E( n , s);
v.push_back(E);
}
sort2(v);
for(int i = 0 ; i < n ; i++ )
{
if( v[i].salary < n2 ) break;
cout << v[i].name << " " << v[i].salary << "\n";
}
return 0;
}
@mehulbhandari358 here they used a class to define employee but you can use a simple pair datatype also. make a pair of pair<int, string> type and use STL sort function on it
can we use sort on class employeee
Look at the sort2 and lol function, that’s what is being done here
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
yeah i have seen it but in “lol” function that part of code is not needed as “>” this can we used directly because of operator overloading
i am asking can i use it directly . due to operator overloading ?
The operator overloading is done here to compare the strings. Otherwise they would be compared according to lexicographical order
that’s what we want , to compare acc. to lexicographical order