I'm fairly new to C++, so I'm having a hard time understanding some complex terms such as Macros and Preprocessors. The code that I can't understand is attached below:
#define NP 2
#define MAX 2000
typedef pair<int, double> edge;
vector<edge> vec[NP][MAX];
What I can't understand here is, what does the vector really store and what does [NP][MAX] determine?
There is not "a vector" — there are many vectors. Many!
Just as int foo[5]
creates an array of five int
s, and int foo[5][10]
creates a two-dimensional array of fifty int
s total…
… vector<edge> vec[5][10]
creates an array of fifty vector<edge>
s.
Now add on the macros: that's just text substitution (more or less), so the array dimensions are being provided via a constant name rather than right there as numbers in the declaration.
So it's a vector<edge> vec[2][2000]
, or four thousand vector<edge>
s.
The type edge
is an alias for pair<int, double>
(thanks, typedef
!), so it's really:
vector<pair<int, double>> vec[2][2000].
This is probably not what was actually intended. Though there is nothing illegal about arrays of vectors, they're a bit of a "double-positive". The vector is already an array-like thing, and it seems likely that the author wanted to create a sort of "two-dimensional vector", but did it wrong. We cannot know this for sure, though, without asking them.