Ctime

When i use the header ctime and then write
srand(static_cast<unsigned int>(time(0));
what does this "time" do?

It returns the current time (usually as the number of seconds since 1970)
A little more specifically, time(0) returns the number of seconds since 00:00:00 Jan 1, 1970 GMT.
1
2
3
4
5
6
7
8
9
10
11
12
13
int z[5][5];
  
  srand(static_cast<unsigned int>(time(0)));
  
  for(int i=0;i<5;i++)
  {
    for(int i=0;i<5;i++)
    {  
      z[i][j]=rand()%41+1;
	     	cout<<setw(3)<<z[i][j];
	}
    cout<<endl;
  }
In this case for example
Last edited on
The purpose is to try in a fairly simple way to make sure that the sequence of random numbers is different each time the program is run, by supplying a different seed value to srand().
Thx Chervil :D
There are many alternatives to ctime that have a richer, more flexible, type-safe interface, e.g., boost.Chrono, or std::chrono.

If you decide you want more specific sampling, e.g., from a specific distribution from a specified range, consider boost.Random https://theboostcpplibraries.com/boost.random.

Note's about your above code sample:
1. Use std::array's rather than c-array's for type-safety when accessing/storing data.
2. Consider alternatives to ctime that provide specific types that accomplish the same results.
3. Avoid nested for-loops utilising counters of the same name (here, its a typo however).
4. Consider manipulating the output stream once outside the loop then resetting it at the end (if desired).
5. Be explicit with namespace scope (i.e., std::cout, not using namespace std;...cout << ....
6. Post-incrementation of counters brings you nothing here, just a needless copy. Use the pre-increment op.
Topic archived. No new replies allowed.