# Thread: How do we sort structs?

1. ## How do we sort structs?

Hi I am trying to input data from a text file into a struct. The problem I am having is how do we sort an entire struct so that the one with the lowest integer is first?

Here is data that I have inputted into the struct of array:
http://i54.tinypic.com/2cmofav.png

As you can see I want it so that the order is Blue, Red, and Green. So that when I type in cout >> Color[0].name[0] >> " " >> Color[0].num[0]; it will output "Blue 1" instead of "Red 50"

Thank you.

2. Presumably by using sort with a comparator function that compares the int members of the struct first (or perhaps only, if you know that all the #s are unique or don't care about ties).

(EDIT: I'm assuming when you say "an entire struct" that you are sorting an array of structs, because you'll generally be treating a struct as a single object.)

3. This is what my struct looks like:

Code:
```struct Candy
{
int modelNumber[10];
double cost[10];
};```
Candy test[4]; //There are four arrays of struct Candy.

So how would I sort it so that the struct with the lowest average cost is first [0 in the array] while the one with the highest average cost is last [3 in the array]. Please help.

4. You write a function that takes two Candy objects and
1. Computes the average cost of each
2. Compares the two values and
3. Returns that information to you in a way of your choosing.

You might return that information as true/false (this is the way most standard functions expect, where you function acts like "<" returning true if the first one is less than the second one), or you could return the difference in costs (so negative would mean the first one is smaller), or whatever you choose.

You can then use that in any sorting mechanism you like. You can use the built-in sort, or build your own (bubble sort is the usual place to start).

5. Thank you for the quick reply. That is exactly where I am stuck. I figured out how to calculate the average cost and compare them. But I don't know how to sort it. Do I use for loops and junk variables to swap the arrays within the structs such as int modelNumber and double cost?