How do I sort an array of struct?

For example:

struct data
{
string city;
string state;
int zip;
};

data listing[];

Recommended Answers

All 6 Replies

Also, does the entire struct move when you sort it or do you have to move each item of the struct in the array? Thanks.

You can sort your array by an one field. Compare the same fields into two objects in the array. And then use Bubble sort, for example.

But, i suggest you to use std::vector for keeping that structures. In this case you need to overload a < operator in your structure. After that just call sort method for your vector.

look at the 4th post on this link.
It shows you one way to sort a struct.

Thanks but no luck. The closest i'm getting is with one error. It doesn't recognize the .state part of populationArray[].state. This is a struct array with elements inside the struct of course. Nothing is recognizing the elements in a sort. Once again, I appreciate your help I'm just a C# programmer not a C++ programmer. Now I've had to switch languages and its throwing me off.

I've tried Bubble Sorts and Selection sorts and even the a/b sort in the previous post to no avail.

Thanks for your efforts

You need a compare function and a swap function:

int compare (data item1, data item2)
{
  // returns -1 if item1 is "before" item2
  // returns 0 if item1 and item2 have "equal" value regarding ordering
  // returns 1 if item2 is "before" item1

  // You'll have to decide the criteria for "equal" and "before"
}

void swap (data& item1, data& item2)
{
  // swap values of each struct element of data1 and data2.
}

Then just do a bubble sort on the array like you would with a primitive type like an integer, only use these functions.

Thanks but no luck. The closest i'm getting is with one error. It doesn't recognize the .state part of populationArray[].state.

I assume there is an index in there?

data populationArray[5];
int i = 2;
populationArray[].state  = "CA"; // incorrect
populationArray[0].state = "CA";// correct
populationArray[i].state = "CA";// correct
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.