I have defined an array of pairs of elements using struct and I'm trying to call (and sort) it using one of the elements (I'm not sure if element is the right term for it) for example, I have

typedef struct { string name; int votes; } candidate;

and I want to sort the array candidates based on increasing order of votes.

is there a way I can do it?

thanks in advance

1 Answer 1


There are many many ways of sorting an array. Sorting an array of structs (I assume that you're doing exactly that) is the same as sorting an array of integers or any other data type. This is taught in the class, or can be found by a simple google search on 'sort array'. You just need to sort the array on the desired field in the struct. In this case, that would be the value stored in votes.

Your question is too broad to provide a simple answer here, other than to say to review the class material on sorting.

If you're having trouble implementing a sort, you need to at least attempt it and post your code here so that we may help you with any errors.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .