【问题标题】:Shuffling an array in c++ [duplicate]在C++中洗牌一个数组[重复]
【发布时间】:2011-01-03 01:56:42
【问题描述】:

可能重复:
How exactly should I implement a shuffle or random-number algorithm for an array to display quotes in random order?

我有一个小数组,我需要在数组中随机打乱这些值。我可以使用 random.shuffle() 在 python 中执行此操作,但我似乎可以弄清楚如何在 C++ 中执行此操作。

这是我想在 C++ 中做的 python 示例

#!/usr/bin/python import random array = [1,2,3,4,5] random.shuffle(array) print array

【问题讨论】:

标签: c++ python


【解决方案1】:

您可以从<algorithm> 使用std::random_shuffle

这是页面中的一个基本示例:

#include <algorithm>                                                                                                    
#include <vector>                                                                                                       
#include <iostream>                                                                                                     
#include <iterator>                                                                                                     

int main()                                                                                                              
{                                                                                                                       
   const int SIZE=10;

   // create and initialize an array                                                                                                   
   int arr[] = {1,2,3,4,5,6,7,8,9,10};                                                                                  

   std::random_shuffle(arr, arr+SIZE);      

   // copy the contents of the array to output                                                                            
   std::copy(arr, arr+SIZE, std::ostream_iterator<int>(std::cout, " "));                                                
   std::cout << std::endl;                                                                                              

   // shuffling an std:: container, here it's std::vector                                                                                         
   std::vector<int> ivec(arr, arr+SIZE);                                                                                
   std::random_shuffle(ivec.begin(), ivec.end());                                                                       
   std::copy(ivec.begin(), ivec.end(), std::ostream_iterator<int>(std::cout, " "));                                     
}        

您可以使用任何使用随机访问迭代器的东西来做到这一点,例如 std::vectorstd::deque 或只是像上面这样的普通数组。

【讨论】:

  • 我不希望结果是随机数,它需要对数组中的固定数字进行洗牌。基本上改组数组中数字的位置
  • @FrozenWasteland:这正是std::random_shuffle 所做的......它会随机播放数组/容器的内容。
  • @birryree 代码我看懂了,但是 ostream_iterator 是从哪里来的,它不会编译。
  • @FrozenWasteland - 更新了一个完整的工作示例。 SGI 的示例代码非常简单,没有显示完整的标头包含等等。
  • 附带说明,如果熵很重要,请使用允许您将函数对象作为随机源传递的重载,或者std::shuffle
猜你喜欢
  • 1970-01-01
  • 2013-08-30
  • 2013-04-13
  • 1970-01-01
  • 2018-08-31
  • 2017-06-24
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多