I have an array of pointers (to a class) which I want to have sorted. I have
implemented the < operator for the class but I guess STL sort will sort the
pointers according to _their_ values (the addresses). Or will it work as I
intended? Do you know ways to circumvent the problem?
Thanks,
Matthias
If you mean to sort the pointers based on the sort order of objects of the
class type, then there's an idiomatic way to deal with that in C++: use the
form of std::sort that takes a function object, and pass in a function
object that takes pointers of the appropriate type and returns true if the
object referred to by the first pointer is "less than" the object referred
to by the 2nd. I happen to have an example program from a past newsgroup
posting handy that illustrates this:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class object {
public:
object(char *s) : name(s) {}
string name;
};
// not used here:
bool operator<(const object &a, const object &b)
{
return a.name < b.name;
}
bool cmp(const object *a, const object *b)
{
return a->name < b->name;
}
ostream &operator<<(ostream &os, const object &o)
{
return os << o.name;
}
int main()
{
vector<object *> v;
v.push_back(new object("this"));
v.push_back(new object("is"));
v.push_back(new object("a"));
v.push_back(new object("test"));
std::sort(v.begin(), v.end(), cmp);
cout << *v[0] << endl;
cout << *v[1] << endl;
cout << *v[2] << endl;
cout << *v[3] << endl;
delete v[0];
delete v[1];
delete v[2];
delete v[3];
return 0;
}
HTH,
-leor