Reputation: 1155
I have a structure coord
and a vector containing objects of type coord
:
struct coord
{
int x1;
int x2;
};
vector<coord> v[n];
Now when I try to put something(just after vector declaration) into vector
v using v[0].x1=2
then compiler gives an error saying
'class std::vector<coord, std::allocator<coord> > has no member named x1'
but when I use a temp
object of coord
type to store coordinates, define vector like
vector<coord> v //i.e without specifying size of vector
,push it into vector and then try to access v[0].x1
, it works fine.
So why I am not able to put into vector using first way but second way?
Upvotes: 1
Views: 145
Reputation: 124790
You declared an array of vectors, not a single vector, so v[n]
returns a vector. You should have called the constructor with a size_t
argument.
vector<coord> v(size);
Upvotes: 3
Reputation: 362117
To create a vector of size n
use parentheses, not square brackets.
vector<coord> v(n);
Using brackets creates an array of n
vectors rather than a vector with n
coordinates.
Upvotes: 4