How can I iterate through a for loop randomly?

So I have a vector that I want to iterate through randomly, and by random I mean that each element is only accessed once but I don't want to shuffle the vector because the vector elements are large.

So I want this functionality:

1
2
3
4
5
6
7
8
9
std::vector<SomeLargeObjectWithoutACopyConstructor> myvec;

// ...fill myvec

std::random_shuffle(myvec.begin(),myvec.end());
for (auto& value : myvec)
{
  // do stuff
}


Only I don't want to do this because the object type has no copy constructor and is large, so I don't want to shuffle the vector, just the iteration path. Is there a simple and efficient way of iterating randomly through a vector while ensuring that each object is only accessed once?
Shuffle a vector of indicies and iterate that.

EDIT: See JLBorges' solution below.
Last edited on
Ok that's logical, cheers.
> Shuffle a vector of indicies and iterate that.

C++11: shuffle a vector of reference wrappers and iterate that.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>

int main()
{
    const std::vector<int> myvec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
    std::vector< std::reference_wrapper< const int > > indirect
                                             { myvec.begin(), myvec.end() } ;
    std::random_shuffle( indirect.begin(), indirect.end() ) ;
    for( const auto& r : indirect ) std::cout << r << ' ' ;
}


http://liveworkspace.org/code/fJtMB$0
Topic archived. No new replies allowed.