I have this code:
const int maxnodes = 5000;
struct Edge
{
int to, rev;
int f, cap;
};
vector g[maxnodes];
This is qui
I believe others have already explained what each line does well. I'm just pointing out that in the second line,
Edge &e = g[u][j];
the code places the Edge at g[u][j] in a reference, presumably, to make the following code easier to both read and write (instead of repeating g[u][j] multiple times).
It is a C-array of vectors
Example with maxnodes = 5.
G[5]
0 -> std::vector<Edge>
1 -> std::vector<Edge>
2 -> std::vector<Edge>
3 -> std::vector<Edge>
4 -> std::vector<Edge>
If each element of g contains 5 elements, it would look like this
G
-
0 -> {0, 1, 2, 3, 4}
1 -> {0, 1, 2, 3, 4}
2 -> {0, 1, 2, 3, 4}
3 -> {0, 1, 2, 3, 4}
4 -> {0, 1, 2, 3, 4}
Meaning, g[u][j], for example with g[2][3] would correspond to the third element in the vector at the second element of g.
g[2][3]
G
-
0 -> {0, 1, 2, 3, 4}
1 -> {0, 1, 2, 3, 4}
2 -> {0, 1, 2, ***3***, 4}
3 -> {0, 1, 2, 3, 4}
4 -> {0, 1, 2, 3, 4}
1) int nodes = maxnodes, src, dest;
Here, nodes is an int initialized with the value same as that of maxnodes. src and dest are also int, but with no initial value.
2) vector<Edge> g[maxnodes];
g is here an array of std::vector.
Edge &e = g[u][j];
Q. What is g[u][j]?
A. It is the Edge stored in g at the uth row and jth column.
Q. g is vector filled with Edge struct, how can it be act like a array of arrays?
A. Because std::vector has operator[] overloaded for itself in its definition. Refer: http://en.cppreference.com/w/cpp/container/vector/operator_at
int nodes = maxnodes, src, dest;
Here nodes, src, dest are all integers where nodes is initialized with maxnodes others are not initialized.
vector<Edge> g[maxnodes];
As @milleniumbug mentioned g is a C array of vectors:
g[u][j] will give i th element of u th element of array g. As u the element of g is a vector where you can access its members using [] operator.
int nodes = maxnodes, src, dest;
This means all are integer and nodes is initialized with maxnodes
vector<Edge> g[maxnodes] is the array of vector.
Vector is like a dynamic array. g[x] will be pointing to a vector. g[x][y] will point to a Edge .
This
int nodes = maxnodes, src, dest;
is a declaration that is equivalent to these three declarations
int nodes = maxnodes;
int src;
int dest;
This
vector<Edge> g[maxnodes];
is a declaration of an array of objects of type std::vector<Edge>. You can use the subscript operator with arrays.
So expression g[u] yields the element of the array with index u that is a reference to an object of type std::vector<Edge>.
Class std::vector also overloads the subscript operator. So expression
g[u][j] gives the object of type Edge with index j in the vector of the array with index u.
Dcelaration
Edge &e = g[u][j];
declares a reference to this object of type Edge.