-
cannot sort structure !
i am unable to compile this code..can any 1 help
Code:
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
struct fraction
{
int num,den;
fraction(){}
fraction(int a,int b) {insert(a,b);}
void insert(int a,int b)
{
int g=__gcd(a,b);
if(g!=0) {a/=g;b/=g;} // reducing to lowest terms !
if(b<0) {a=-a;b=-b;} // changing the sign !
num=a;den=b;
}
bool operator <(fraction A)
{
return (num*A.den-den*A.num<0);
}
bool operator >(fraction A)
{
return (num*A.den-den*A.num>0);
}
bool operator ==(fraction A)
{
return (num*A.den-den*A.num==0);
}
};
int main()
{
fraction a[100];
sort(a,a+100);
return 0;
}
Thank you !
-
If you were unable to compile the code, then presumably there was some message involved.
-
Done
Code:
bool operator <(const fraction &A) const
changing to the above works .but donno why ?
-
Because you can't call non-const functions on constant or temporary objects. (Temporary would be the key here, I'm guessing.)
-
It might depend on the implementation. You can look it up from the error, where it happens in particular. With GCC (first) error occurs in this function:
Code:
template<typename _Tp>
inline const _Tp&
__median(const _Tp& __a, const _Tp& __b, const _Tp& __c)
As you can notice your object is passed by const reference to a function that uses your operator<.
In general, it is absolutely necessary that comparing objects doesn't change them (imagine objects were changing while you are sorting them!), and C++ uses the const keyword to enforce that this requirement is met.