samedi 18 avril 2020

C++ Can you traverse a vector with for, if for-code potentially expands same vector?

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);

Aucun commentaire:

Enregistrer un commentaire