0

I have a struct which looks like this:

struct employee
{
    char name[21], surname[21];
    unsigned int salary;

}employees[20];

My question is, how would I sort this array of structs by the field "name", sorting them alphabetically.

I've seen people use sort() or qsort(), but I don't know how to make the compare() that you usually have to make for those sorting algorithms.

MickeyMoise
  • 259
  • 2
  • 13

1 Answers1

3

Just use a lambda expression as for example

#include <iterator>
#include <algorithm>
#include <cstring>

//...

std::sort( std::begin( employees ), std::end( employees ),
           []( const auto &em1, const auto &em2 )
           {
               return strcmp( em1.name, em2.name ) < 0;
           } );

Instead of the character arrays used as data members in the structure it is much better to use objects of the type std::string.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335