(I know you (or someone) updated the question to fix the lack of typedef
s - just leaving this as relevant to the original question in case it helps someone else).
You need to understand the difference between a type and an object/variable/instance of that type. For example, double
is a type, and if you say:
double x;
Then you've defined a variable x
of type double
in which you can store one number.
In a sense, types are saying how to use some memory to record a value of that type. Type's aren't told where the memory they're to manage is - that's only done when you define one or more variables of that type.
The templates std::pair<>
and std::vector<>
expect their parameters to be types: for example std::vector<int>
is an instantiation of the std::vector
template for the parameter int
, and is itself a new type which you can use to create a variable:
std::vector<int> vi;
So, to your code:
std::pair< double,double > A;
std::vector< A > B;
std::vector< B > C;
The first line creates a variable called A
of type std::pair<double,double>
.
The second line tries to instantiate std::vector<>
with the variable from the last line, which won't work - the std::vector<>
template must be instantiated with a type. To make it work, we need:
typedef std::pair< double,double > A;
std::vector< A > B;
The typedef
keyword indicates that the first line is creating an alternative name for std::pair<double, double>
, so the above definition for the variable B
is entirely equivalent to:
std::vector< std::pair<double, double> > B;
Then your next line repeats the just-fixed mistake the second line made, of instantiating a template with a variable. To fix the code to create a two-dimensional vector:
typedef std::pair< double,double > A;
typedef std::vector< A > B;
std::vector< B > C;
Which creates a variable C
of type std::vector<std::vector<std::pair<double,double>>>
.
If you're certain the vectors inside C
have sufficient size()
for i
and j
to be valid indices, then you can access the individual doubles
using:
C[i][j].first;
C[i][j].second;
Otherwise, you can attempt to access indices i
, j
and have the compiler throw an exception if either the outer or inner vector is too small:
try
{
std::cout << C.at(i).at(j).first << ' ' << C.at(i).at(j).second << '\n';
}
catch (const std::exception& e)
{
std::cerr << "caught an exception " << e.what() << '\n';
}