I've a function to generate random characters from a set of alphabets. This function would be called multiple times and thus I'm trying to make it use same set of variables, ie have same seed so that strings don't repeat as long as possible.
#include <iostream>
#include <random>
#include <string>
std::string generateRandomChar(const unsigned int _len)
{
std::string result;
result.reserve(_len);
static constexpr char alphanum[] = "0123456789"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::random_device rd;
std::mt19937 gen(rd());
for (int i = 0; i < _len; i++) {
std::uniform_int_distribution<> dis(0, 61);
result += (alphanum[dis(gen)]);
}
return result;
}
int main(){
for(int i = 0; i < 10; ++i){
std::cout << generateRandomChar(10) << std::endl;
}
}
Unfortunately I don't have any expertise with c++11 functions and I was only using srand
and friends earlier, so I might be making lots of mistakes here. Currently it works and generates tons of strings without repeating, but I'm sure I could make either of -
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 61);
static variable too, so that it isn't calculated each time the function is called because that would be waste right?
So which one should be static here? Are there any mistakes/improvements that you see here?
Thankyou :D
edit - here's an ideone link - http://ift.tt/2cnIdC8
Aucun commentaire:
Enregistrer un commentaire