Sorting objects in a vector?

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?
Look up std::sort() in the algorithm header, I believe.
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
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.
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.
But I thought you couldn't just assign an object to another object?
What? Why shouldn't you be able to?
Well I thought there was some problem in C++ with copying the contents of an object to another.
Probably not, but is something like this possible?

 
players[i] ^= players[i+1] ^= players[i] ^= players[i+1];
That has undefined behavior, as you are modifying variables twice between sequence points. Break it up into multiple lines and it should be fine.
Zhuge, I've used that method to swap variables in an INT array before. Why can't it be applied to a vector?
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.
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.