C++ output elements of a vector not expected

75 Views Asked by At

I'm practicing vector and ranged for loop, my code:

#include <iostream>
#include <vector>
using namespace std;

int main(){
    int size,element;
    cout<<"enter vector size: ";
    cin>>size;
    vector<int>v(size);
    for(int i=0; i<size; i++){
        cout<<i<<"\t";
        cin>>element;
        v.push_back(element);
    }
    for(int p : v) cout<<p<<" ";
}

I entered 3 then 1, 2, 3 but the output is "0 0 0 1 2 3". Could you please explain me where the 0s are from? Thank you very much!

2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER
vector<int>v(size);

This creates a vector of having size equal to size variable. Now if you do push_back it will create a new vector and with size+1 and add the element to it. Instead inside for loop do cin>>v[i];

4
Paul Sanders On

vector<int>v(size); creates a vector of size zero-initialised elements (in your case 3). push_back then adds new elements to the end of this vector, which explains the results you get.

You can reserve space for elements in the vector with reserve. This speeds things up somewhat if you know in advance how many elements you will be adding.