Vector sort on Z value

What I'm trying to accomplish is pretty simple. I have a vector full of instances of my class:

vector<Particle> particles;

and im sorting that vector using a comp function:

1
2
3
bool sortByZ(const Particle &a, const Particle &b){
    return a.z<b.z;
}


then I perform the sort itself:

sort(particles.begin(),particles.end(),sortByZ);

but when I loop through the vector after the sort it doesn't appear to have sorted the instances by their Z value.

1
2
3
for(int i=0;i<particles.size();i++){
        printf("%f\n",particles[i].z);
}



what am I missing here?
Looks good to me.

Hm.. maybe... IIRC, std::sort uses std::swap to swap two objects, which in turn looks something like

1
2
3
4
5
6
swap(T a, T b)
{
    T x(a);
    a = b;
    b = x;
}


so make sure your copy constructor and assignment operator for Particle works as expected.

Ciao, Imi.
Thanks for your reply Imi.

I've printed out the results of the sort function and it appears to be grabbing the Z values of the 2 instances it's comparing properly. It also evaluates correctly if the first instance ("a")'s Z value is less than the second instance ("b"). It just doesn't appear to be sorting the vector at all based on the return data. hmmm
Let's take a look at the assignment operator=. Show us the particle class. Perhaps it cannot be copied properly. It is better to post a complete, compilable example. All that we need to see is the complete particle class, predicate, and a simple main function that inserts some values into the vector and then sorts it. This should be a really simple problem to diagnose but we cannot do that without seeing a complete example. I'm betting that the problem is that your objects aren't being copied properly.
Looks like it's working. Not sure what I did differently but it's sorting them properly now. thanks for the assistance.
*chrm*.... .... And if you run into an uncommon cave-eat and solved it, it's usually nice to tell the others what caused the problem and what was your solution. You know.. for all those people coming with the same problem from google via "c++ sort doesn't work" or something like that ;-)

Ciao, Imi.
Topic archived. No new replies allowed.