0

The wiki says:
The elements of a vector are stored contiguously. AND
Vectors allow random access; that is, an element of a vector may be referenced in the same manner as elements of arrays (by array indices).

So why can't we input the elements of a vector as:

vector<int> v;
for(int i=0;i<3;i++)
{
    cin>>v[i];
}
2
  • 2
    If you give the vector a size, yes. Otherwise it starts with 0 elements. If you have a fixed size, you can use std::array instead. But what is wrong with push_back? Commented Dec 10, 2014 at 14:46
  • @crashmstr given the number of questions on here about it I would add the caveat that if you have a fixed size and that size can fit on the stack you can use std::array instead. Commented Dec 10, 2014 at 14:53

3 Answers 3

4

Either you need to resize the vector upfront - as other answers say - or you can use C++ standard library. Then the equivalent of your for loop is the following one line:

copy_n(istream_iterator<int>(cin), 3, back_inserter(v));

and it takes care of allocation/resizing.

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

Comments

3

Your vector has zero elements right now. Try allocating it some space as:

vector<int> v(5);

Then your method would work.

Comments

3

The problem is that you need to allocate the elements of the vector first. So try vector<int> v(4);, so it will start with 4 elements. Then you can load values into them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.