-2

I am a C++ beginner. I want to understand how is this function operating on a string to sort it?

int SA_cmp(const void *a, const void *b) { return strcmp(S + *(int*)a, S + *(int*)b); }

any pointer will help?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 5
    A word of advice: abandon the above and go with the [std::string](http://en.cppreference.com/w/cpp/string/basic_string) and [std::sort](http://en.cppreference.com/w/cpp/algorithm/sort). – Ron Sep 15 '17 at 09:22
  • 3
    What is `S`? Whatever learning material you are using: Throw it away NOW. Get a [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead. That is terrible code and should not be shown to a beginner. – nwp Sep 15 '17 at 09:23

2 Answers2

2

That's a C comparison function, not a (C++) sorting function. A sort function (probably qsort, given the const void* arguments) would call it a number of times (passing it pointers to what are apparently indices into a buffer containing a number of null-terminated strings) in order to sort those indices (and, indirectly, the substrings they indicate).

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
1

This will not sort a string.

This is a method that helps comparing strings and is used by sorthing methods as a helper method.

It will return a negative number if string a is lexicographically smaller than string b, 0 if they are equal, or a positive number if b is greater than a.

gsamaras
  • 71,951
  • 46
  • 188
  • 305