How do i sort a class in a vector?

Hey guys

How do i sort a classes in a vector?
This is my example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

class player{
public:
	player(string n, int s):
	  name(n), score(s){}

	string name;
	int score;
};

player newplayer(string n, int s)
{
	return player(n,s);
}

int main()
{
	vector<player>players;

	players.push_back(newplayer("Assassinbeast",200));
	players.push_back(newplayer("Pikachu",300));
	
	for(int i = 0; i < players.size(); ++i)
		cout << players[i].name << " -> " << players[i].score << endl;

	//sort(players.score.begin(), players.score.end());

	for(int i = 0; i < players.size(); ++i)
		cout << players[i].name << " -> " << players[i].score << endl;

	char cc; cin >> cc;
	return 0;
}


As you can see, i try to sort the playerclass in the vector so the player with the lowest score gets in the lowest position in the vector (players[1] should get changed to players[0]). I commented it out because its an error, but you can see what im trying to do

Ive tried to figure out how to do it, but now i give up :P need some help here :)
Last edited on
std::sort uses operator< to compare two objects by default so you could overload operator< for your class if that makes sense.
1
2
3
4
bool operator<(const player& p1, const player& p2)
{
	return p1.score < p2.score;
}


sort(players.begin(), players.end());

Or you could use another comparison function that you pass to std::sort as the third argument.
1
2
3
4
bool playerScoreCmp(const player& p1, const player& p2)
{
	return p1.score < p2.score;
}


sort(players.begin(), players.end(), playerScoreCmp);
Last edited on
Topic archived. No new replies allowed.