Created
June 10, 2013 22:23
-
-
Save koturn/5752947 to your computer and use it in GitHub Desktop.
bsearch()関数で文字列を探すサンプルコードです。
This file contains hidden or 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> | |
// Macros for restrict-qualifier under various environmets | |
#if _MSC_VER >= 1400 // In Visual C++ (after Visual C++ 2005), | |
# define restrict __restrict // 'restrict' and '__inline__' aren't available | |
# define __restrict__ __restrict // but '__restrict' is. | |
#elif __cplusplus // In language C++ (but not Visual C++), | |
# define restrict __restrict // 'restrict' isn't available but '__restrict' is. | |
#elif !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L | |
# if defined(__GNUC__) // In gcc, | |
# define restrict __restrict // 'restrict' isn't available but '__restrict' is. | |
# else | |
# define restrict // If 'restrict' isn't available, remove 'restrict' | |
# define __restrict // as well as '__restrict' | |
# define __restrict__ // and '__restrict__'. | |
# endif | |
#endif | |
// LAMBDA for C/C++ | |
#if defined(__cplusplus) | |
# define LAMBDA(rettype, ARG_LIST, BODY) \ | |
([&]ARG_LIST -> rettype { BODY; } ) | |
#elif defined(__GNUC__) && !defined(__clang__) | |
# define LAMBDA(rettype, ARG_LIST, BODY) \ | |
({ \ | |
rettype __lambda_funcion__ ARG_LIST { \ | |
BODY; \ | |
} \ | |
__lambda_funcion__; \ | |
}) | |
#else | |
# error You have to compile with gcc or C++0x Compiler!! | |
#endif | |
#define LENGTH(array) (sizeof(array) / sizeof((array)[0])) | |
#ifndef __cplusplus | |
# define ARRAY_SIZE 40 | |
#else | |
static const int ARRAY_SIZE = 40; | |
#endif | |
int main(void) { | |
const char *table[] = { | |
"Japan", | |
"America", | |
"Italy", | |
"Thailand", | |
"Mexico", | |
"Russia" | |
}; | |
char str[ARRAY_SIZE]; | |
char target[ARRAY_SIZE]; | |
char **search_result; | |
qsort(table, LENGTH(table), sizeof(char *), | |
LAMBDA(int, (const void *restrict a, const void *restrict b), { | |
return strcmp(*(char **)a, *(char **)b); | |
}) | |
); | |
puts("Input string for search."); | |
fgets(str, sizeof(str), stdin); | |
sscanf(str, "%s", target); | |
search_result = (char **)bsearch(target, table, LENGTH(table), sizeof(char *), | |
LAMBDA(int, (const void *restrict key, const void *restrict elm), { | |
return strcmp((char *)key, *(char **)elm); | |
}) | |
); | |
if (search_result == NULL) { | |
printf("'%s' was not found.\n", target); | |
} else { | |
printf("'%s' was found!!\n", target); | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment