swap string

I would like to create a ranking list based on scores. For example, I used structure to declare the variables. After values has entered, the program supposed to show the list in decreasing order. However, I have no idea on how to swap the name with the scores into such order. My output was exactly the same as my input. Which means the first person I entered will remain as first person and so the others.

My output:

Enter name 1: kenneth
Enter score: 100
Enter name 2: ruby
Enter score: 90
Enter name 3: joshua
Enter score: 133
Enter name 4: mina
Enter score: 25
Enter name 5: max
Enter score: 67

ranking list
1 kenneth
2 ruby
3 joshua
4 mina
5 max


instead of this output:

ranking list
1 joshua
2 kenneth
3 ruby
4 max
5 mina


How can I get those output?
I had tried to swap strings together with the scores. But it came to compile error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <vector>
#include <algorithm>

[...]

struct Score
{
  string name;
  int score;
  bool operator<(const Score& rhs) const {return score>rhs.score;}
};

[...]

vector<Score> scores;
//enter scores here
sort(scores.begin(),scores.end());
I not really understand how this code works, can I have an example on how to display or setting those statement for the ranking problem? Thank you very much.
Hello..y read you're code and figured out one way to do it..it is a simple way,because y am a beginner(not just like the one above witch uses some functions from libraries ),but hope it's good.

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
struct Player{
        char Name[20];
        int Score;
};

int main ()
{
	int NrPlayers=5,c,i;
	/*the Aux value must be struct type,
	 so you can assign the struct to it when you swap: Aux=tab[i]; 
	 */
	struct Player Aux;
	struct Player tab[5];
	for(i=1;i<=NrPlayers;i++){
		printf("Enter name %d: ",i);
		scanf("%s",&tab[i].Name);
		printf("Enter score: ");
		scanf("%d",&tab[i].Score);
	}
	do{
		c=0;
		for(i=1;i<=NrPlayers;i++)
			if(tab[i].Score < tab[i+1].Score){ // remember:you compare the score,
				Aux = tab[i];                        // but you switch the whole structure
				tab[i] = tab[i+1];
				tab[i+1] = Aux;
				c=1;
			}
	}while(c==1);

	for(i=1;i<=NrPlayers;i++)
		printf("%d %s\n",i,tab[i].Name);

	system("PAUSE");
	return 0;
}


now this is a simple bubble sort,and it has some bugs.it will not sort 100% all the time,but you can replace it with any sorting algorithm you want,the condition in the if and the swap is the same..and also be careful when you make space for the number of players,in the for loops.don't start the sorting from 0 to <n,and other from 1 to<=n,it may cause you exe to crack and don't now what goes wrong.
Y hope this is what you where looking for,and good luck :)
Last edited on
thanks a lot for this information. It is more easier to understand. thank you. ^^
Topic archived. No new replies allowed.