red floyd wrote:

laniik wrote: ok i did some research and am now introduced to the wonderful world of

functors, but its not entirely clear to me how this works.

i have a functor:

class compare

{

public:

vector<object>* objects;

bool operator ()(const int p1,const int p2)

{

return((*objects)[p1].x < (*objects)[p2].x);

}

};

and in my main

...

sort(indices.begin(),indices.end(),compare());

...

Why use a pointer to the vector in your functor? Why

not use a reference?

The functor should ideally be stateless. And in fact it could be if the

indices vector stored iterators of the container holding objects,

instead of integer indices. For the indices vector to store iterators,

the iterators would have to be stable. Iterators for a vector do remain

valid most of the time, but increasing the size of a vector can

invalidate all of its iterators.

Since the indices vector already offers the benefits of vector storage,

why not change objects to a different type of container, one with

stable iterators? Doing so would make compare so simple it could become

just an ordinary function (if desired), and the whole implementation

would be more self-maintaining:

#include <vector>

#include <list>

#include <algorithm>

using std::vector;

using std::list;

struct object

{

int val;

};

bool

compare( const list<object>::iterator& i1,

const list<object>::iterator& i2 )

{

return (*i1).val < (*i2).val;

}

int main()

{

list<object> objects;

vector<list<object>::iterator> indices;

std::sort( indices.begin(), indices.end(), compare);

return 0;

}