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:
As you can see I want it so that the order is Blue, Red, and Green. So that when I type in cout >> Color.name >> " " >> Color.num; it will output "Blue 1" instead of "Red 50"
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.)
This is what my struct looks like:
Candy test; //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.
You write a function that takes two Candy objects and
- Computes the average cost of each
- Compares the two values and
- 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).
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?