Structure in an array

How do I pass 96 random numbers generated into a structure with 2-D array?

A record is needed to record the actual and expected output of 4 machines for 12 months.

struct MachineType
{
int actualOutput, expectedOutput;
};

MachineType MT[4][12];

TIA
Implement struct with typedef as follows :

Nested Structures :

1
2
3
4
5
6
7
8
9
10
typedef struct Machine
{
	int ActualOutput;
	int ExpectedOutput;
} Output;

struct Record
{
	Output Month[12];              //typedef 'struct Machine' for 12 months as an array
} a[4];                                        // 4 such machine's records 
Last edited on
Using typedef struct is redundand and frown upon in C++. Also iostream.h do not exist in C++ for 17 years.
Thanks TheCplusplusMan, but I must use 2 D array
Use nested loops:
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
#include <iostream>
#include <random>

struct MachineRecord
{
    int actualOutput;
    int expectedOutput;
}; 

MachineRecord random_record()
{
    static std::mt19937 rng(std::random_device{}());
    static std::uniform_int_distribution<> dist(1, 30); //Output can be in range [1; 30]
    return MachineRecord{dist(rng), dist(rng)};
}

int main()
{
    constexpr int machines = 4;
    constexpr int months = 12;
    MachineRecord MT[machines][months];
    //Fill array
    /* 
     * for(int i = 0; i < 4; ++i) for(int j = 0; j < 12; ++j)
     *  MT[i][j] = random_record();
     */
    for(auto& row: MT) for(auto& m: row)
        m = random_record();

    //Output
    /*
     * for(int i = 0; i < 4; ++i) {
     *   for(int j = 0; j < 12; ++j)
     *       std::cout << MT[i][j].actualOutput << ':' << MT[i][j].expectedOutput << ' ';
     *   std::cout << '\n';
     * }
     */
    for(auto& row: MT) {
        for(auto& m: row)
            std::cout << m.actualOutput << ':' << m.expectedOutput << ' ';
        std::cout << '\n';
    }
}
7:10 25:8 27:24 25:17 13:13 8:19 18:1 18:23 24:3 25:3 26:9 22:8 
16:21 4:12 18:22 28:20 30:27 12:7 9:18 2:24 6:10 19:17 7:5 20:20 
21:26 18:22 20:5 11:7 21:15 26:24 16:13 27:25 19:12 3:10 6:8 5:18 
29:6 10:1 2:26 19:7 15:15 7:9 6:6 14:9 9:15 9:20 9:8 4:27 
http://coliru.stacked-crooked.com/a/4634e63f6d8e733b
Without adding srand(time(0)) i get a set fixed of 96 random numbers. However if I add srand, I only have 4 sets of 24 same numbers which are different every time I compile. Please advise.

MachineType random_record()
{
int output1, output2;


for (int i = 0; i < 96; i++)
{
output1 = rand();
output2 = rand();

}

return MachineType{ output1, output2 };
}

Make sure that you calling srand only once in your whole program. Best place for it* is in the beginning of main().

* It is not recommended to use rand at all, and in fact it coud be removed in future versions of C++ standard.
Last edited on
Thank you!!
Topic archived. No new replies allowed.