lundi 23 juillet 2018

How to read from a file, populate a vector and choose a random element in that vector

I would like to see the right and fast approach to handle this problem. I've been assigned a project. The project is to design a GUI where the user start picking a random number loaded from a big file (i.e. 52MB). This file has five millions numbers. The following code generates this data file.

#include <iostream>
#include <fstream>
#include <random>

int main () {
  std::ofstream out;
  out.open ("data.txt");
  std::random_device rd;  
  std::mt19937 gen(rd()); 
  std::uniform_int_distribution<> dis(0, 9);
  for(long i(0); i < 5000000; ++i){
      for (int j(0); j < 10; ++j)
        out << dis(gen);
    out << '\n';
  }
  out.close();
  return 0;
}

My approach is to load them in a vector and randomly choose an element in that vector. After running the GUI, I've noticed filling the vector takes 4 seconds which causes the GUI to hang. What I would like to do is to fill the vector and show the random numbers at the same time so that whenever the user wants to pick a random number, the user will press stop button. What is the right approach to handle this problem? I've thought about multithreading where a thread will fill a vector and another thread will pick a random number but I can't create an atomic vector type.

Aucun commentaire:

Enregistrer un commentaire