在C++中打乱数组

1 投票
1 回答
2068 浏览
提问于 2025-04-16 09:19

可能重复的问题:
我应该如何实现一个洗牌或随机数算法,以便在数组中随机显示引用?

我有一个小数组,我需要把里面的值随机打乱顺序。在Python中,我可以用random.shuffle()来做到这一点,但我不知道在C++中该怎么做。

下面是我想在C++中实现的Python示例:


#!/usr/bin/python

import random

array = [1,2,3,4,5]

random.shuffle(array)

print array

1 个回答

15

你可以使用来自 <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,或者像上面那样的普通数组。

撰写回答