Sorting objects in a vector?

Mar 19, 2011 at 12:22am
I'm writing a program that requires me to sort a vector of objects. I already know how to compare two objects in the vector based on a member variable, but how would I swap the two objects in the vector?

Is there a vector function for such a thing?
Mar 19, 2011 at 12:27am
Look up std::sort() in the algorithm header, I believe.
Mar 19, 2011 at 12:37am
As zhuge said, you can easily sort stuff with std::sort.

Also, there is std::swap to swap two values - vectors also have a member function swap, however it swaps out values between two vectors, not two values in the same vector.

Anyways, swapping values in general can be done like that:
1
2
3
4
5
6
swap(a,b)
begin
c=a
a=b
b=c
end
Mar 19, 2011 at 12:59am
I would rather not use an outside function.
I want to do know how to do it without using that header file.
I've got the sorting function all written out except for the swap part.
Mar 19, 2011 at 1:12am
As I said, std::swap or just swap the values normally... Create a temporary variable that stores one of the values, then assign one value to the other, and then assign the temporary value to the first.
Mar 19, 2011 at 1:17am
But I thought you couldn't just assign an object to another object?
Mar 19, 2011 at 1:23am
What? Why shouldn't you be able to?
Mar 19, 2011 at 1:38am
Well I thought there was some problem in C++ with copying the contents of an object to another.
Mar 19, 2011 at 1:40am
Probably not, but is something like this possible?

 
players[i] ^= players[i+1] ^= players[i] ^= players[i+1];
Mar 19, 2011 at 2:02am
That has undefined behavior, as you are modifying variables twice between sequence points. Break it up into multiple lines and it should be fine.
Mar 19, 2011 at 2:32am
Zhuge, I've used that method to swap variables in an INT array before. Why can't it be applied to a vector?
Mar 19, 2011 at 1:45pm
I just want to be clear. You guys know I'm not sorting a vector of a simple data type, right? It's a vector of a class object. I just tried the temporary variable thing and it didn't work.
Mar 19, 2011 at 1:59pm
I tried the swap() function in the algorithm header and it's still not working.

1
2
3
4
5
6
7
8
9
10
11
12
13
void sortInitiative(vector<initiative>& init_order, int numOfPlayers)
{
	for(int i = 0;i < (numOfPlayers - 1);i++)
	{
		for(int j = i+1;j < numOfPlayers;j++)
		{
			if(init_order[j].getPlayerInit() > init_order[i].getPlayerInit())
			{
				swap(init_order[i], init_order[j]);
			}
		}
	}
}
Topic archived. No new replies allowed.