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, StrictWeakOrder<auto, Iter::value_type> Compare> 13 // requires ShuffleIterator<Iter> 14 // && CopyConstructible<Compare> 15 // void 16 // nth_element(Iter first, Iter nth, Iter last, Compare comp); 17 18 #include <algorithm> 19 #include <functional> 20 #include <vector> 21 #include <random> 22 #include <cassert> 23 #include <cstddef> 24 #include <memory> 25 26 #include "test_macros.h" 27 28 struct indirect_less 29 { 30 template <class P> 31 bool operator()(const P& x, const P& y) 32 {return *x < *y;} 33 }; 34 35 std::mt19937 randomness; 36 37 void 38 test_one(int N, int M) 39 { 40 assert(N != 0); 41 assert(M < N); 42 int* array = new int[N]; 43 for (int i = 0; i < N; ++i) 44 array[i] = i; 45 std::shuffle(array, array+N, randomness); 46 std::nth_element(array, array+M, array+N, std::greater<int>()); 47 assert(array[M] == N-M-1); 48 std::nth_element(array, array+N, array+N, std::greater<int>()); // begin, end, end 49 delete [] array; 50 } 51 52 void 53 test(int N) 54 { 55 test_one(N, 0); 56 test_one(N, 1); 57 test_one(N, 2); 58 test_one(N, 3); 59 test_one(N, N/2-1); 60 test_one(N, N/2); 61 test_one(N, N/2+1); 62 test_one(N, N-3); 63 test_one(N, N-2); 64 test_one(N, N-1); 65 } 66 67 int main() 68 { 69 int d = 0; 70 std::nth_element(&d, &d, &d); 71 assert(d == 0); 72 test(256); 73 test(257); 74 test(499); 75 test(500); 76 test(997); 77 test(1000); 78 test(1009); 79 80 #if TEST_STD_VER >= 11 81 { 82 std::vector<std::unique_ptr<int> > v(1000); 83 for (int i = 0; static_cast<std::size_t>(i) < v.size(); ++i) 84 v[i].reset(new int(i)); 85 std::nth_element(v.begin(), v.begin() + v.size()/2, v.end(), indirect_less()); 86 assert(static_cast<std::size_t>(*v[v.size()/2]) == v.size()/2); 87 } 88 #endif 89 } 90