cl333r
May 7th, 2009, 03:17 PM
Folks can anyone please make this sorting example work? It compiles and runs, but doesn't actually sort the elements from the vector.. I spent a few hours and can't figure out what's the matter..
main.cpp:
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include "Person.h"
using namespace std;
int main(int argc, char** argv) {
Person *p1 = new Person( "James" );
Person *p2 = new Person( "Brian" );
Person *p3 = new Person( "John" );
Person *p4 = new Person( "Mark" );
vector<Person*> v;
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
std::sort(v.begin(), v.end());
cout << "Sorted: " << endl;
for( int i=0; i<v.size(); i++) {
Person *p = v.at(i);
cout << p->getName() << endl;
}
return (EXIT_SUCCESS);
}
Person.h:
#ifndef _PERSON_H
#define _PERSON_H
#include <iostream>
#include <glibmm.h>
using namespace std;
class Person {
public:
Person(Glib::ustring);
virtual ~Person();
Glib::ustring getName();
bool operator<(Person* other) {
cout << "called operator < for" << getName() << endl;
return other->getName().compare(name) > 0;
}
protected:
Glib::ustring name;
};
#endif
Person.cpp:
#include "Person.h"
Person::Person(Glib::ustring s) {
name=s;
}
Person::~Person() {}
Glib::ustring Person::getName() {
return name;
}
main.cpp:
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include "Person.h"
using namespace std;
int main(int argc, char** argv) {
Person *p1 = new Person( "James" );
Person *p2 = new Person( "Brian" );
Person *p3 = new Person( "John" );
Person *p4 = new Person( "Mark" );
vector<Person*> v;
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
std::sort(v.begin(), v.end());
cout << "Sorted: " << endl;
for( int i=0; i<v.size(); i++) {
Person *p = v.at(i);
cout << p->getName() << endl;
}
return (EXIT_SUCCESS);
}
Person.h:
#ifndef _PERSON_H
#define _PERSON_H
#include <iostream>
#include <glibmm.h>
using namespace std;
class Person {
public:
Person(Glib::ustring);
virtual ~Person();
Glib::ustring getName();
bool operator<(Person* other) {
cout << "called operator < for" << getName() << endl;
return other->getName().compare(name) > 0;
}
protected:
Glib::ustring name;
};
#endif
Person.cpp:
#include "Person.h"
Person::Person(Glib::ustring s) {
name=s;
}
Person::~Person() {}
Glib::ustring Person::getName() {
return name;
}