1

I tried using rand() with srand() to generate random index numbers but i still get indices repeating is there any other way of iterating over all elements of a vector buy getting the indices randomly without affecting order of vector elements I cant random_shuffle() because random shuffle changes the order of my vector elements whose order is critical.

Oblivion
  • 7,176
  • 2
  • 14
  • 33
Tony Mogoa
  • 21
  • 2
  • 1
    Stop using `rand()` and start [using ``](https://stackoverflow.com/a/13445752/1870760). – Hatted Rooster Oct 17 '19 at 15:07
  • Can you make a copy of the vector and shuffle that instead? – Federico klez Culloca Oct 17 '19 at 15:12
  • I have just tried using `random_device dev; mt19937 rng(dev()); uniform_int_distribution dist6(0, ICSC.size()); // distribution in range [1, 6] cout << dist6(rng) << std::endl;` which still has repetition. – Tony Mogoa Oct 17 '19 at 15:12
  • 3
    So shuffle a vector of indices, and then get your vector elements by index. There isn't a much better way of randomly sampling without replacement that I'm aware of, because you need to track which indices you already consumed. – Useless Oct 17 '19 at 15:14
  • `shuffle()` still destroys the order, because i need every 4 vector elements starting from beginning to stay together. – Tony Mogoa Oct 17 '19 at 15:16
  • Thanks let me try creating an array of indices. – Tony Mogoa Oct 17 '19 at 15:19

1 Answers1

10

Use std::iota to fill a vector with indices. Then use std::shuffle to shuffle the index vector. Use the index vector to iterate your main vector.

Implementation left as practice to the OP.

Oblivion
  • 7,176
  • 2
  • 14
  • 33