1

Is it possible to sort an array of struct (I mean a C-style array, not a std::array), using std::sort or should I use qsort?

P.S. I know, I should use std::vector or std::array instead of using new and delete or to create array with type name [size], but I would like to know anyway.

Nisba
  • 3,210
  • 2
  • 27
  • 46

1 Answers1

3

You can use std::begin and std::end to determine the start and end points of your array, assuming you are on C++11.

So:

int someArray[10]
std::sort(std::begin(someArray), std::end(someArray));
Stuart Thompson
  • 1,839
  • 2
  • 15
  • 17
  • Wow! I did not know that I could use std::begin and std::end this way! – Nisba Oct 09 '17 at 18:47
  • 2
    @Nisba, for a struct you still have to provide a comparison function object as a third parameter which this answer doesn't show. – wally Oct 09 '17 at 18:48
  • @rex oh yes I know that ;) – Nisba Oct 09 '17 at 18:49
  • 2
    @Nisba Ok, good. :) And also remember that it must ensure [strict weak ordering](https://stackoverflow.com/a/10779203/1460794). A [std::tie](https://stackoverflow.com/a/37269108/1460794) might be the easiest way for the struct members. – wally Oct 09 '17 at 18:51
  • 1
    @rex Thanks for teaching me something new about structs! – Stuart Thompson Oct 09 '17 at 22:50