Created
April 8, 2012 17:03
-
-
Save mietek/2338494 to your computer and use it in GitHub Desktop.
Sorting C strings in C and C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int my_string_compare(const void* a, const void* b) { | |
return strcmp(*(const char**)a, *(const char**)b); | |
} | |
int main() { | |
const char* s[] = {"dalet", "gimel", "bet", "aleph"}; | |
const int n = sizeof(s) / sizeof(*s); | |
int i; | |
qsort(s, n, sizeof(*s), my_string_compare); | |
for (i = 0; i < n; i++) | |
printf("%s\n", s[i]); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <cstdio> | |
#include <cstring> | |
bool my_cstring_less(const char* a, const char* b) { | |
return std::strcmp(a, b) <= 0; | |
} | |
int main() { | |
const char* s[] = {"dalet", "gimel", "bet", "aleph"}; | |
const int n = sizeof(s) / sizeof(*s); | |
std::sort(s, s + n, my_cstring_less); | |
for (int i = 0; i < n; i++) | |
std::printf("%s\n", s[i]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment