F
Frank
Hello everyone,
I am having trouble overloading the < operator for an assignment. I
use a struct that contains information and I would like to sort this
structure using STL sort with my own criteria of sorting. Basically, I
would like to sort on visitor count of the Attraction structure.
However, it never uses the < overloaded operator with my code.
Handler.h:
#ifndef H_HANDLER //Guard
#define H_HANDLER
#include <iostream>
#include <vector>
using namespace std;
struct Attraction {
string name;
int visitors;
};
class Handler { //Define the class Handler
private:
vector<Attraction*> attractions ;
vector<Attraction*>::iterator p ;
public: //Public functions
~Handler();
void addAttraction(string name, int visitors);
void printAttractions();
};
#endif
and in the Handler.cpp I have:
Handler.cpp - snippet:
bool operator<(const Attraction& a,const Attraction& b){
return a.visitors < b.visitors;
}
Here is the function that performs the sort after adding a value:
void Handler::addAttraction(string name, int visitors){
Attraction *attr;
attr=new Attraction();
attr->name=name;
attr->visitors=visitors;
attractions.push_back(attr);
sort(attractions.begin(),attractions.end());
}
However, whatever I do, it will never use the overloaded < operator
for sorting. What am I doing wrong? If I add the overloaded function
in the header it starts complaining because it will also be inserted
into the main program which is confusing since I have a guard around
the header file.
Regards,
Frank
I am having trouble overloading the < operator for an assignment. I
use a struct that contains information and I would like to sort this
structure using STL sort with my own criteria of sorting. Basically, I
would like to sort on visitor count of the Attraction structure.
However, it never uses the < overloaded operator with my code.
Handler.h:
#ifndef H_HANDLER //Guard
#define H_HANDLER
#include <iostream>
#include <vector>
using namespace std;
struct Attraction {
string name;
int visitors;
};
class Handler { //Define the class Handler
private:
vector<Attraction*> attractions ;
vector<Attraction*>::iterator p ;
public: //Public functions
~Handler();
void addAttraction(string name, int visitors);
void printAttractions();
};
#endif
and in the Handler.cpp I have:
Handler.cpp - snippet:
bool operator<(const Attraction& a,const Attraction& b){
return a.visitors < b.visitors;
}
Here is the function that performs the sort after adding a value:
void Handler::addAttraction(string name, int visitors){
Attraction *attr;
attr=new Attraction();
attr->name=name;
attr->visitors=visitors;
attractions.push_back(attr);
sort(attractions.begin(),attractions.end());
}
However, whatever I do, it will never use the overloaded < operator
for sorting. What am I doing wrong? If I add the overloaded function
in the header it starts complaining because it will also be inserted
into the main program which is confusing since I have a guard around
the header file.
Regards,
Frank