nth_element.pass.cpp (1437B)
1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // <algorithm> 11 12 // template<RandomAccessIterator Iter> 13 // requires ShuffleIterator<Iter> 14 // && LessThanComparable<Iter::value_type> 15 // void 16 // nth_element(Iter first, Iter nth, Iter last); 17 18 #include <algorithm> 19 #include <random> 20 #include <cassert> 21 22 std::mt19937 randomness; 23 24 void 25 test_one(int N, int M) 26 { 27 assert(N != 0); 28 assert(M < N); 29 int* array = new int[N]; 30 for (int i = 0; i < N; ++i) 31 array[i] = i; 32 std::shuffle(array, array+N, randomness); 33 std::nth_element(array, array+M, array+N); 34 assert(array[M] == M); 35 std::nth_element(array, array+N, array+N); // begin, end, end 36 delete [] array; 37 } 38 39 void 40 test(int N) 41 { 42 test_one(N, 0); 43 test_one(N, 1); 44 test_one(N, 2); 45 test_one(N, 3); 46 test_one(N, N/2-1); 47 test_one(N, N/2); 48 test_one(N, N/2+1); 49 test_one(N, N-3); 50 test_one(N, N-2); 51 test_one(N, N-1); 52 } 53 54 int main() 55 { 56 int d = 0; 57 std::nth_element(&d, &d, &d); 58 assert(d == 0); 59 test(256); 60 test(257); 61 test(499); 62 test(500); 63 test(997); 64 test(1000); 65 test(1009); 66 }