| 类别:算法 | 组件类型:函数 |
template <class ForwardIterator, class OutputIterator, class Distance>
OutputIterator random_sample_n(ForwardIterator first, ForwardIterator last,
OutputIterator out, Distance n)
template <class ForwardIterator, class OutputIterator, class Distance,
class RandomNumberGenerator>
OutputIterator random_sample_n(ForwardIterator first, ForwardIterator last,
OutputIterator out, Distance n,
RandomNumberGenerator& rand)
复制m从to到范围[out, out + m),其中是从min(last - first, n)。返回值是out + m第一个版本使用一个内部随机数生成器,而第二个版本使用一个 随机数生成器,这是一个特殊类型的 函数对象,它被明确地传递为一个参数。.
定义
int main()
{
const int N = 10;
int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
random_sample_n(A, A+N, ostream_iterator<int>(cout, " "), 4);
// The printed value might be 3 5 6 10,
// or any of 209 other possibilities.
}
N! / n! / (N - n)!种从范围中选择个是非负数。元素的样本的方法N个元素。Random_sample_n产生均匀分布的结果;也就是说,选择任何特定元素的可能性为n / N,任何特定采样的概率为n! * (N - n)! / N!.
[2] 相比之下,random_sample算法不会保留输入范围的相对顺序。这两种算法的另一个主要区别在于random_sample_n需要其输入范围为 向前迭代器,并且仅需要其输出范围为 输出迭代器,而random_sample仅需要其输入范围为 输入迭代器,并且需要其输出范围为 随机访问迭代器。