| 1 |
// Copyright (C) 2016-2025 Free Software Foundation, Inc. |
| 2 |
// |
| 3 |
// This file is part of the GNU ISO C++ Library. This library is free |
| 4 |
// software; you can redistribute it and/or modify it under the |
| 5 |
// terms of the GNU General Public License as published by the |
| 6 |
// Free Software Foundation; either version 3, or (at your option) |
| 7 |
// any later version. |
| 8 |
|
| 9 |
// This library is distributed in the hope that it will be useful, |
| 10 |
// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
// GNU General Public License for more details. |
| 13 |
|
| 14 |
// You should have received a copy of the GNU General Public License along |
| 15 |
// with this library; see the file COPYING3. If not see |
| 16 |
// <http://www.gnu.org/licenses/>. |
| 17 |
|
| 18 |
// { dg-do run { target c++17 } } |
| 19 |
// { dg-require-cstdint "" } |
| 20 |
|
| 21 |
#ifndef _GLIBCXX_ASSERTIONS |
| 22 |
// Make std::uniform_int_distribution check its parameters |
| 23 |
# define _GLIBCXX_ASSERTIONS |
| 24 |
#endif |
| 25 |
|
| 26 |
#include <algorithm> |
| 27 |
#include <random> |
| 28 |
#include <climits> |
| 29 |
#include <testsuite_hooks.h> |
| 30 |
#include <testsuite_iterators.h> |
| 31 |
|
| 32 |
std::mt19937 rng; |
| 33 |
|
| 34 |
using std::sample; |
| 35 |
using __gnu_test::test_container; |
| 36 |
using __gnu_test::output_iterator_wrapper; |
| 37 |
|
| 38 |
void |
| 39 |
test01() |
| 40 |
{ |
| 41 |
int pop[UCHAR_MAX] = { }; |
| 42 |
for (int i = SCHAR_MAX; i < UCHAR_MAX; ++i) |
| 43 |
pop[i] = 1; |
| 44 |
const signed char sample_size = SCHAR_MAX; // PR libstdc++/77994 |
| 45 |
int out[sample_size] = { }; |
| 46 |
|
| 47 |
// random access iterators for both population and result |
| 48 |
// (uses reservoir sampling) |
| 49 |
auto it = sample(std::begin(pop), std::end(pop), out, sample_size, rng); |
| 50 |
auto sum = std::accumulate(out, it, 0); |
| 51 |
VERIFY( sum != 0 ); // exceedingly unlikely! |
| 52 |
|
| 53 |
// random access iterator for population and output iterator for result |
| 54 |
// (uses selection sampling) |
| 55 |
test_container<int, output_iterator_wrapper> samp2(out); |
| 56 |
sample(std::begin(pop), std::end(pop), samp2.begin(), sample_size, rng); |
| 57 |
sum = std::accumulate(std::begin(out), std::end(out), 0); |
| 58 |
VERIFY( sum != 0 ); |
| 59 |
} |
| 60 |
|
| 61 |
int |
| 62 |
main() |
| 63 |
{ |
| 64 |
test01(); |
| 65 |
} |