'Sort structs by char array (name) (c++) [duplicate]
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
