jeudi 26 mai 2016

Randomized selection of vector elements

In MyClass class, the constructor calls generate to set the value of another class member, which works fine. The issue occurs when I try to generate 9(3 X 3) strings from MyClass::generate() when called from another class, using:

OtherClass::OtherClass

  std::vector<MyClass> getString;
  getString.reserve(3);

  for(int j = 0; j < 3; j++){
      for(int i = 0; i < 3; i++){
          MyClass myclass;
          getString.push_back(myclass);
       }
       mapContainer[keyFromVector.at(j)] = getString;
       getString.clear();
   }

MyClass::generate()

std::vector<std::string> listOfString;

std::string MyClass::generate(){

    listOfString = { "string1", "string2",....., "string20" };

    std::random_device random;
    std::mt19937 rand_string(random());
    std::shuffle(listOfString.begin(), listOfString.end(), rand_string);
    std::string getString = listOfString.at(1);

    listOfString.erase(listOfString.begin() + 1);  

    return getString;
}

What I want as output is:

Key1

String1, String5, string7

Key2

String2, string13, string4

Key3

string10, string17, string11

Right now, I get repeated string values from




Aucun commentaire:

Enregistrer un commentaire