Reputation: 12393
In a lot online judge problems, the format for the input is as follows: first line is the number of test cases. Let's say X. Then X lines after that are the conditions for each test case.
In the example below, there are two test cases. Each test case specify the upper and lower bound for which primes should be shown in the output.
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Now for my question. Right now, my program can handle one test case like so:
int main()
{
TestCase t;
t.setRange();
t.compute();
t.print();
}
How can I create X amount of TestCases without naming them all 't'?
X is specified at rumtime.
Upvotes: 1
Views: 488
Reputation: 95614
In C++ you have two options to create objects: stack or heap.
To create it on the stack you'd run a for loop and declare a variable normally like TestCase t
.
The other way is to create it on the heap. This dynamically creates x number of TestCase objects.
TestCase ** tests = new (* TestCase)[x];
for (int i = 0; i < x; i++) {
tests[i] = new TestCase();
} // for i
Upvotes: 0
Reputation: 27581
for (int i = 0; i < numOfTestCases; ++i) {
TestCase t;
t.setRange();
t.compute();
t.print();
}
Upvotes: 0
Reputation: 881565
You can make a std::vector<TestCase> allofem;
and allofem.push_back(TestCase())
X
times; remember to #include <vector>
of course. Then you can loop on allofem
and compute and then print on each item.
Upvotes: 3