1

I am new to the vector class and was exploring ways of inserting elements in a vector as per the user request. I tried a loop to insert ten elements in a vector using push_back() method. But my vector is only storing 9 elements if I start the indexing from zero.

#include<iostream>
#include<vector>

using namespace std;

int main()
{
   vector<int>v1;
   for(int i=0; i<10; i++)
   {
       cin>>i;
       v1.push_back(i);
   }
}

I am using visual studio, and I am only able to insert 9 elements in my vector. What can be the issue?

lakshayg
  • 1,983
  • 2
  • 21
  • 33
ALOK KUMAR
  • 19
  • 2

1 Answers1

4

You are replacing your loop variable i inside of the loop, meaning that you might not get ten iterations. If the user enters 10, you would only get one iteration.

To solve this, you must use a separate variable for reading user input:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v1;
    for(int i = 0; i < 10; i++)
    {
        int input;
        std::cin >> input;
        v1.push_back(input);
    }
}

I also recommend reading Why is "using namespace std;" considered bad practice?

Jan Schultke
  • 5,808
  • 1
  • 22
  • 57
  • Firstly ,Thanks for your response. I am totally aware of the fact the "using namespace std;" is considered a bad practise as it also includes the elements that we may not use at all which will result into wastage of memory. I only use it when I am coding short programs, to skip out writing "std::" again and again. – ALOK KUMAR Aug 28 '20 at 09:27