2

I am new to the std::vector class and was exploring ways of inserting elements into a vector as per the user request. I've tried a loop to insert ten elements in a vector using the push_back() member function, but my vector is only storing nine 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 nine elements into my vector. What can be the issue?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
ALOK KUMAR
  • 29
  • 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
  • 17,446
  • 6
  • 47
  • 96
  • 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
  • @ALOKKUMAR - do 'using std::vector;' – pm100 Jun 16 '23 at 16:59