ソート覚書
今までわざわざ面倒な方法でソートしていた。
こんな簡単にできるのに一体何をやっていたのだろう。
#include "stdafx.h" #define _CRT_RAND_S //の直前に#define すること #include #include #include #include #include class CSizeLess { public: bool operator()(const unsigned int lhs, const unsigned int rhs) const { return lhs < rhs; } }; int _tmain(int argc, _TCHAR* argv[]) { #define LIST_SIZE 50 std::list
list; unsigned int value; for (unsigned int i = 0; i < LIST_SIZE; ++i) { ::rand_s(&value); list.push_back(value); } // std::sort(list.begin(), list.end(), CSizeLess()); list.sort(CSizeLess()); std::list ::iterator iter = list.begin(); std::list ::iterator iterEnd = list.end(); while (iter != iterEnd) { std::cout << *iter << std::endl; ++iter; } return 0; }
一応qsortで試したものも掲載。
#include "stdafx.h" #define _CRT_RAND_S #include#include int compareFunc(void *context, const void *param1, const void *param2) { unsigned int num1 = *(unsigned int *)param1; unsigned int num2 = *(unsigned int *)param2; if (num1 < num2) { return -1; } else if (num1 > num2) { return 1; } return 0; } int _tmain(int argc, _TCHAR* argv[]) { #define ARRAY_SIZE 50 unsigned int num[ARRAY_SIZE]; unsigned int *p = num; unsigned int value; for (unsigned int i = 0; i < ARRAY_SIZE; ++i) { ::rand_s(&value); *p++ = value; } ::qsort_s(num, ARRAY_SIZE, sizeof(int), compareFunc, NULL); for (unsigned int i = 0; i < ARRAY_SIZE; ++i) { _tprintf_s(_T("%u\n"), num[i]); } return 0; }