在迭代随机顺序阵列上方 [英] Iterating over the array in random order

查看:137
本文介绍了在迭代随机顺序阵列上方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于 N 元素(比如的std ::矢量 T *序列),是否有遍历其随机顺序的元素,访问每个元素恰好一次的有效途径。该解决方案必须避免造成与洗牌指数附加阵列。

Given a sequence of N elements (say std::vector or T*), is there any efficient way to iterate over its elements in random order, visiting each element exactly once. The solution must avoid creating additional array with shuffled indices.

编辑:

此外,我们需要能够跟踪原始索引

Also we need to be able to track original indices

推荐答案

使用的std :: random_shuffle ,所以你code会喜欢这样的:

Use std::random_shuffle, so you code will like this:

std::random_shuffle ( myvector.begin(), myvector.end() );  // in place no extra array
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
   std::cout << ' ' << *it;

这篇关于在迭代随机顺序阵列上方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆