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!
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];