我有一个小数组,我需要在数组中随机改组.我可以使用random.shuffle()在python中执行此操作,但我似乎可以弄清楚如何在C++中执行此操作.
这是python中我想用C++做的一个例子
#!/usr/bin/python
import random
array = [1,2,3,4,5]
random.shuffle(array)
print array
wkl*_*wkl 15
您可以使用std::random_shuffle从<algorithm>.
以下是该页面的基本示例:
#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, " "));
}
Run Code Online (Sandbox Code Playgroud)
你可以使用任何使用随机访问迭代器的东西,比如std::vector或者std::deque像上面那样的普通数组.
| 归档时间: |
|
| 查看次数: |
1191 次 |
| 最近记录: |