0

First of all, I want my user to tell me how many numbers he have to input? Which will create that number of elements in vector initialized to zero. Then I want to use for-range loop to insert the elements into the vector and similarly an other for-range loop to display the vector elements.

#include<iostream>
#include<vector>
using std::cout;
using std::vector;
using std::cin;

int main(){
  int c;
  cin>>c;
  vector<int> ivec(c); 
  
  for(int i : ivec){ //for taking input and adding it into vector 
    cin>>i;
    ivec.push_back(i);
  }

  for(int i: ivec){ //displaying the vector 
    cout<<i<< "\t";
    }
 

  return 0;
}

but my output is very different from my expectation.

My actual output is coming as:-

Output :-

3
4
5
6
0 0 0 4 5 6 

can somebody explain me please? And can I actually use a for-range loop for inserting vector elements?

Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 1
    Is the output you show the *actual* or *expected* output? If it's the actual output, then what's the expected output? And what is the input that causes the unexpected output? – Some programmer dude Jun 23 '21 at 07:23
  • 1
    And have you tried to *debug* your program? Like for example stepping through the code, statement by statement, in a debugger while you monitor variables and their values? – Some programmer dude Jun 23 '21 at 07:24

1 Answers1

5

std::vector have 2 sizes. One is actual-used size and the other is reserved-size.

Below creates a vector with actual-size n.

std::vector<int> v(size_type n)

While this creates a vector with empty size and reserved size n.

std::vector<int> v;
v.reserve(n);

std::vector<T>::push_back() increases the actual-size by 1 at the end.
So your code is

  1. Create a vector with actual-size c.
  2. Add element at the back.

So you should replace your code to

std::vector<int> vec(c);
for(auto& i : ivec){
  cin>>i;
}

This creates a vector with size c and modifies its element.

Or

std::vector<int> vec;
for(int i=0; i<c; ++i) {
  int temp;
  std::cin >> temp;
  vec.push_back(temp);
}

where this creates an empty vector and pushes the element at the end.

See cppreference for more info.

김선달
  • 1,485
  • 9
  • 23
  • Yes it's working thank you, But can you explain me why I need to use reference here? and why my code isn't working. I didn't get what you said ? I know it will create vector of size c already then how ivec.push_back(i) is pushing after that vector? – Shubharthak Jun 23 '21 at 07:30
  • 1
    @Shubharthak `std::vector` has 2 sizes. One is the actual used size, and the other is the capacity size which is pre-allocated memory size. I think you're confusing both. I'll add more description in my answer. – 김선달 Jun 23 '21 at 07:34