random numbers

closed account (SECMoG1T)
Hi am having a problem trying to generate random numbers in my program and I need some help.

Here is my situation. I made a class and each object of the class got a function called getrandom () that returns a random number,
I then made a vector of three objects and used a loop to examine the numbers generated per object , to my amazement all three objects generate the same number and that number is only random between different program runs

Is there anyway that each of my three objects could generate indipendent
Random number within the same loop, below is my code for clarity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 #include <iostream>
 #include <ctime>
 #include <cstdlib>

 using namespace std;

 struct foo
  {
    foo ():value(0){}
    int getrandom() {srand (time(NULL)); return( rand()%100);}
    int value; 
  };

  int main()
   {
       vector<foo> vec {3};
    
       for( size_t i=0; i <10; ++i)
        {
           cout<<vec[0].getrandom()<<" "<<vec[1].getrandom()<<" "
               <<vec[2].getrandom()<<endl;
        }
 
        return 0;
     }
Last edited on
srand should only be called once in the lifetime of your program, take it out of line 10 and put it before line 16.
int getrandom() {srand (time(NULL)); return( rand()%100);}time() result changes relatively rarely whn compared to the speed of code execution. That means that in your loop 10 calls to time() will probably yield same result. So you wil reseed rng with same seed making next value the same for every call. You should not call srand more than once in your program. Move call to it to the beginning of the main().
closed account (SECMoG1T)
@lowestone and @minnippa well you people are awesome haha,
When I moved srand to main it works just fine as I wanted , that is all I
Wanted but is there another way of generating random numbers if there is
Mybe I can weigh between them and srand for the most effective one.
I'll be very glad to if you can give me a clue.
srand()/rand() are usually uses pretty crappy RNG. Also rand() % something fails at providing uniform distribution.

C++11 provides a whole library for random number handling, <random>.It provides a bunch of tweakable generators (However you should use only std::mt19937 unless you have a good reason to use something else). And many distributions. Honestly it has everything you need.
http://en.cppreference.com/w/cpp/numeric/random
Like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <random>
#include <iostream>
#include <ctime>

int gen_random(int low , int high)
{
    static std::mt19937 gen(std::time(nullptr));
    std::uniform_int_distribution<> dis(low, high);
    return dis(gen);
}

int main()
{
    std::cout << gen_random(1, 6) << '\n' << gen_random(-10, 10);
}
I used std::time because MinGW does not implemented std::random_device properly. If your compiler supports it, use it instead.
http://en.cppreference.com/w/cpp/numeric/random/random_device
closed account (SECMoG1T)
Well this is amaizing , I knew there was another way out coz I dont trust srand so much
Haha, mean while I'll be looking into this random yeah. But I know one day i'll be
Better as you @minnippa haha. Thank you for the help.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include<vector> 
 
int main()
{
std::vector<int>vec{3}; // should vec(3)
vec[0]=1;
vec[1]=2; //overflow
vec[2]=3; //overflow

std::cout << vec[2] << " size: " << vec.size();	
    
}
closed account (SECMoG1T)
@anup30 I guess this std::vector<int>vec{3}; /// should vec(3) is not wrong
New standard ( uniform intialization) and gives you even extra allowance for inclass
Container intialization . Generally I prefer it to vec(3) c++ 11. Plus I don't get where the
1
2
vec[1]=2; //overflow 
vec[2]=3; //overflow  

Is from, please help me understand.
Last edited on
There is a problem with uniform initialization: if it is possible to threat parameters as initializer list, it would do so.

As vector do have constructor which takes initializer_list<T>, Init list for int would clash with constructor which takes int or two ints.
So vector<int> x{3} creates a vector with single element with value 3.
vector<int*> y{3} creates a vector with 3 null elements.
closed account (SECMoG1T)
#$# getting confused now where should I use uniform intialization only on user defined types without a constructor that would conflict with inti list? Now I dont know which.
I can see the point @anup30 was making then.
Last edited on
Just remember this. Soon you will remember what STL classes has to offer you and will notice such traps.

Using braces initialisation or uniform initialization is a matter of preference, but there are some places where only one of them can be used. Pick one and fall back to other when needed. I personally prefer braces.
closed account (SECMoG1T)
Well i guess i am still becoming better here . Question here ,so I av realised
Or av confused myelse that built in types too have constructors
1
2
3
4
5
6
int main ()
 {
    int x (7);            /// constructor? ?
    double d (1.6); /// is this a constructor? 
    string  str ("hello world") /// this am sure it is.
  }


If the above were constructors I would be the most confused
Person ever coz I use them always yet I dont know whet they are.
Last edited on
built-in initialization might look like constructor call, but it is not.
http://stackoverflow.com/a/5113429/3410396
closed account (SECMoG1T)
Well now understand those aren't constructors.@minnippa what should
I do to learn the best of c++ and avoid all this flaws and misconceptions
Or should i just stick to what am learning till the real thing reveal itself
Through experience . How did you learn all this youself?? . Advice will be greatly appreciated.
Last edited on
Bumped into many common problems, listened programmers who knew better, read many books on programming, spent many hours rummaging through C++ standard trying to find explanation for specific behavior, googled a lot...
closed account (SECMoG1T)
Thank you for advice , I know soon i'll be good enough too forget about the intimidating
Bugs I come across day after another. Thenks i'll read hard , i am sure you people had such challeges
While learning.
Last edited on
Topic archived. No new replies allowed.