How to write (rand)

Nov 8, 2013 at 8:24pm
Please is theere a way to write this shorter?

1
2
3
  int a=rand();
int b=rand();
int c=rand();


Many thanks!
Nov 8, 2013 at 8:27pm
You can improve it a bit by doing this:
int a = rand(), b = rand(), c = rand();

-Albatross
Nov 8, 2013 at 10:26pm
If you're talking about having multiple variables that are similar... then naming them with incremental names (like 'a', 'b', 'c') is almost always a bad idea.

You're usually better off using an array:

1
2
3
4
5
6
7
8
9
int values[3];

for( auto& x : values )
    x = rand();

// or... if you're still living in the past and can't use basic C++11 features yet...
//   this for loop is equivalent:
for( int i = 0; i < 3; ++i )
    values[i] = rand();


While this isn't "shorter", it scales up much better. So if you need to change it so you have 20 variable instead of just 3... all you have to do is make the array bigger. Whereas if they all had unique names, you'd have to copy/paste a bunch of code.
Nov 9, 2013 at 7:39am
Hello!
I have to get more random numbers, but with each I have to do different operations.

Is there any way to "generate" more automatically different names for each of the random number?


Can I write: for (int i=int a; i<=z; a++) ???

Or shoul dit be somehow connected with "char" ?

Many thanks!

Last edited on Nov 9, 2013 at 7:51am
Nov 9, 2013 at 8:09am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>

int main()
{
    std::srand( std::time(nullptr) ) ; // seed the C lcg

    unsigned int z ;
    std::cout << "how many random numbers? " ;
    std::cin >> z ;

    std::vector<int> numbers(z) ; // vector of z numbers

    // fill it up with 'z' random numbers
    std::generate_n( numbers.begin(), z, std::rand ) ;

    // or: fill it up with 'z' random numbers
    for( int& v : numbers ) v = std::rand() ;
}
Topic archived. No new replies allowed.