There are constructs that you cannot do in C++, and others, that you should not do.
C++ does not support VLA, Variable Length Arrays. An array like defined by you in `int c[m][n1];'. Both 'n1' and 'm' are variable. They are not compile time constants. But, this is a requirement in C++. So, it will not work.
Regarding passing arguments to a function. There are basically 3 methods:
- Pass by value. Like you do in your function. A copy will be made of all parameters that you hand in. And the outside world does not see any modification done to these variables in the function.
- Pass by pointer. Which is in essence also pass-by-value, but here the address of a variable will be passed (by value). And, if we dereference the address, we can access the addressed value and modify it. So, the modification will be visible outside the function. You will then see the '*'-symbol besides the parameter.
- Pass by reference. In your case, the best solution. A reference to the original variable will be passed to the function, and if you then modify the variable in the function, the referenced value (outside) the function will be updated. Additionally, no data will be copied. This save time and space. You will see the '&' beneath a variable.
So, you can define a vector<vector<int>> c
outside your function. You can initialize it as you want and then pass it by reference to your function body.
This has the additional advantage, that the vector knows its size. And you do not need to hand in the parameters m
and n1'. You can get the number of elements in a
vectorby using its
size()'-function.
It looks a bit complicated to define and initialize a 2d vector
. Therefore, I will show this to you using one of its constructors.
vector<vector<int>> c(m, std::vector<int>(n1, 0));
This will define a 2d vector
with the needed number of elements and initialize everything to 0.
You can then define your function, for example, like this:
int ordonnancer(int n, vector<vector<int>>& p, vector<int>& ind, vector<vector<int>>& c) {
Please note that I pass all vector
s per reference. See the '& symbol.
And in your function, you can get back the size of the 2d-vector
for your loop with:
size_t m = c.size();
By the way, you should not use using namespace std;
. Instead, you should use fully qualified names like std::vector
.
Should you need further help, please comment