views:

106

answers:

4

I have a struct like this:

struct db {
 string name,sur;
 int num;
};

And declared an array of db structs:

struct db a[10];

and every member of a[] is filled with a name, surname and a number but there can be the same number appearing multiple times. I need to sort the numbers, and print the results, i.e. sort by the num of each struct and the print the name, sur and the num in each line starting from the smallest num going down to the largest. I don't know how to do this, please help me.

+4  A: 

You can use qsort.

int db_comparator ( const void * elem1, const void * elem2 )
{
  struct db *first = (struct db *) elem1, *second = (struct db *) elem2;
  return first->num - second->num;
}

qsort(a, sizeof(a)/sizeof(a[0]), sizeof(a[0]), db_comparator);
Matthew Flaschen
+1: standard C way of doing things
Iulian Şerbănoiu
...but not the standard C++ way. `std::sort` is strongly typed and (often) faster. It's also undefined behaviour to use `qsort` on non-POD data, such as structures containing `std::string`.
Mike Seymour
+6  A: 

First, in C++ you don't need to repeat "struct" every time.

You can use the std::sort() function and give it a custom predicate.

bool db_cmp(const db &left, const db &right)
{
    return left.num < right.num;
}

//...

db a[10];
std::sort(a, a + 10, db_cmp);
// then, display the contents of a..
Etienne de Martel
+1  A: 

Do you have to implement your own sorting algorithm?

If so I strongly suggest typing "Sorting Algorithms" into google and/or checking out the wikipedia page.

Bubble sort is REALLY easy to implement (But is a poor sorting algorithm). It will come down to checking each number against each other and then swapping them is one is less than the other. String sorting is easy too as strcmp returns you a value less than 0 for a string "less" than the one being compared to and greater than zero for one "greater" than.

If you don't need to implement your own algorithm then use std::sort.

Goz
A: 

You could add a comparison method to your structure:

struct db
{
  string name;
  string sur;
  int    num;

  bool operator <(const db& other)
  {
    if (name == other.name)
    {
      return sur < other.sur;
    }
    return name < other.name;
};

Now you can use the std::sort algorithm because your object has the '<' operator defined.

Thomas Matthews