0

In below example, I've seeded a generator so that 'distr(eng)' yields a random number within a range determined by the number of letters in a word (obtained from user-input (cin >>)).

I want the vector 'brr' to hold the randomly generated numbers.

The objective furthermore is to avoid duplicates, so that a cin of a word with 7 characters results in a vector with 7 randomly generated numbers (within the determined range) that are all different from each other. My code gives no errors, but when I print out the vector 'brr' nothing happens (appears to be empty). Variable 'numberofletters' is not in signed/unsigned conflict with .size().

brr = { 0 };

do
{
    int z = distr(eng);
    int* pz = &z;

    for (it = brr.begin(); it != brr.end(); ++it)
    {  
      if (*it = *pz)
      {
        brr.insert(it, *pz);
      }
      else
      {
        brr.push_back(*pz);
      }
    }
}
while (brr.size() < numberofletters);
bruno
  • 32,421
  • 7
  • 25
  • 37
user359294
  • 61
  • 1
  • 4
  • 2
    if (*it = *pz) --> shouldn't it be ==? – SPD Apr 18 '20 at 07:59
  • 3
    If you want random values in a range AND without duplicates, better to generate all values in the range (e.g. in a vector) and then use an appropriate random number generator to help shuffle it. Since C++11, there is `std::shuffle()` and before C++11 there is `std::random_shuffle()`. – Peter Apr 18 '20 at 08:04

1 Answers1

3

The simple answer is NO!

Any insert to a std::vector can invalidate all iterators of the vector as the full content can be moved, if the vector must reallocate its memory.

From std::vector::insert

Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.

Klaus
  • 24,205
  • 7
  • 58
  • 113
  • Found a duplicate (https://stackoverflow.com/questions/35938329/c-push-back-in-stdvector-while-iterating-it). – user359294 Apr 18 '20 at 22:47