1

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

capacity and size has a different meanings in the context of std::vector, and what the vector<T> (size_type n) constructor does is create a vector of size n filled with n default-constructed elements. On the other hand, a vector with capacity c may well contain less than c elements. I know you are aware of that and using it as a variable name only but I think in this context it would be good to change it to avoid confusion later.
@us2012: You're right, it was a sloppy use of the word capacity. I'll fix it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.