简体   繁体   中英

Memory allocation for objects in a vector

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?

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.

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM