0

I've created a class, let's call it classA. I want to create in function main() a random number of objects. How can I do this whilst naming them differently? I've tried out of desperation:

int a[100],i ,rnd;

srand ( time(NULL) ); 

rnd=(rand() %100);      
for(i=0;i<=rnd;i++){
    classa a[i];
}

but I knew it would not work.

Zong
  • 6,160
  • 5
  • 32
  • 46
aalepis
  • 3
  • 1

2 Answers2

5

Use something like this:

std::vector<a> v(rand() % 10000);  // creates [0, 10000) objects
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 2
    Except use `std::uniform_int_distribution` and `std::mt19937` to avoid modulo bias. –  Nov 27 '13 at 20:22
  • 1
    @rightfold One talk and suddenly rand() is evil :). Is it uniform after modulo ? - no (usually not, that is). Do you actually care? I'd dare to claim you usually don't. – ScarletAmaranth Nov 27 '13 at 20:25
  • @ScarletAmaranth No, it was problematic before then, but I guess the problems are getting wider coverage now. I [was](http://stackoverflow.com/a/8157725/365496) [recommending](http://stackoverflow.com/a/8317726/365496) [against](http://stackoverflow.com/a/9485149/365496) usage of `rand()` and in favor of `` pretty much since C++11 was finished, citing the many of the same issues as STL pointed out in his presentation. – bames53 Nov 27 '13 at 20:38
  • `rand()` was and still is fine. You just have to know its weaknesses. Sure you can use stuff from `` for more accurate random numbers (is that an oxymoron?) but it comes with a price. For simple stupid things like this rand() (and modulo) are still fine. – Martin York Nov 27 '13 at 20:41
  • @bames53 ofcourse it existed before, shees, this was supposed to point out the recent wider coverage actually... just nevermind :). – ScarletAmaranth Nov 27 '13 at 20:50
  • @ScarletAmaranth What I mean is that even before that presentation these problems were brought up in pretty much every question that mentioned `rand()`. Now it's still brought up in every thread, just maybe by more users. – bames53 Nov 27 '13 at 20:53
  • 1
    @rightfold: There was no requirement for uniformity. The OP already seems to have decided a mechanism for getting randomness... – Kerrek SB Nov 27 '13 at 21:13
  • @KerrekSB and how will I be able to refer to those objects? I was hoping for something like "obj[i]" or so, so I can use every object separately. – aalepis Nov 27 '13 at 21:47
0
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);

std::map<std::string, a> objects;

for (int i=0; i < dis(gen); ++i)
      objects.insert(std::make_pair("obj_"+std::to_string(i), a()));
4pie0
  • 29,204
  • 9
  • 82
  • 118