conorjh

Just another WordPress.com site

Relational functions, classes and sort in C++

If you are defining your own relational function for use in sort, why do it have
to be a global function, rather than a class method.

Why is it that this works:


#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

bool comp(const int & x,const int & y){return x>y;}
class Foo
{
public:

Foo(vector<int> a){this->a=a;sort(this->a.begin(),this->a.end(),comp);}
void print(){for(unsigned int i=0;i<a.size() ;++i){cout<<a[i]<<" ";}cout<<endl;}
private:
vector<int> a;
};

int main()
{
vector<int> a(3,3);
a[1]=1;
a[2]=2;

Foo foo(a);
foo.print();
}

when what's below doesn't.


#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

class Foo
{
public:
bool comp(const int & x,const int & y){return x>y;}
Foo(vector<int> a){this->a=a;sort(this->a.begin(),this->a.end(),comp);}
void print(){for(unsigned int i=0;i<a.size() ;++i){cout<<a[i]<<" ";}cout<<endl;}
private:
vector<int> a;
};

int main()
{
vector<int> a(3,3);
a[1]=1;
a[2]=2;

Foo foo(a);
foo.print();
}

Another question is, if the objects being compared, the object you have a vector of, are themselves a class, why can't you just overload the "<" operator in the class?

Advertisements

Single Post Navigation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s