Return two values from a function

I have this code that generates two numbers and stores them in two separate arrays.

If the random numbers are not allowed it generates two numbers again and is pass to another function duplicate() to check if the numbers are allowed and calls it self recursively to check the numbers again.

The problem is how will I store the return statement of the duplicate() function into two variables since I will use that variables as index for the array in the random function?

Any tips and hints??



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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

void duplicate(int n1, int n2)
{
  if((n1 == 4) && (n2 == 3))
  {
        b = rand() % 7;
        c = rand() % 4;

        duplicate(b, c);
  }
  else if(// other index that are not allowed //)
   {
     b = rand() % 7;
     c = rand() % 4;

     duplicate(b, c);
   }
   else
   {
     return n1, n2;
   }

}

void random(int a[][4])
{
 srand(time(NULL));

 int first[4];
 int second[4];

 for( i = 0; i < 4; i++)
 {
   first[i] = rand() % 7;
   second[i] = rand() % 4;

   if((first[i] == 4) && (second[i] == 3))
   {
     b = rand() % 7;
     c = rand() % 4;

     duplicate(b, c);
   }
   else if(// other index that are not allowed //)
   {
     b = rand() % 7;
     c = rand() % 4;

     duplicate(b, c);
   }
   else
   {
     cout << first[i] << " ";
     cout << second[i] << " ";
            
     cout << a[first[i]][second[i]] << "\n";
   }

}
I can think of 2 ways to return 2 values. The first is with a struct.

1
2
3
4
5
6
7
8
9
10
struct TwoValues
{
    int first;
    int second;
};

TwoValues func()
{
    ...
}


By the way, std::pair is the template form of this. You could use, instead:

1
2
3
4
5
6
#include <utility>

pair<int, int> func()
{
    ...
}


The second method is to return values in reference arguments. This is similar to what you have, but you are missing the reference indicators ('&').

1
2
3
4
void func(int& first, int& second)
{
    ...
}
Ok thanks I will try what you suggested :)
Topic archived. No new replies allowed.