Heisenberg
Heisenberg

Reputation: 5299

cin didnt work in range based loop in vector

I tried to input values to my vector,but it filled with zero value. I try to input value by following range based loop and output them.

#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0; i<(n); i++)
 
int main() {
    int N;
    cin>>N;
    vector<int>A(N);
    for(auto x:A) cin>>x;
    for(auto y:A) cout<<y<<' ';
    cout<<endl;
    return 0;
}

output is following , N=2 vector=1 2 but output is 0 0

root@DESKTOP-TM0ASL2:~/work# ./a.out 
2   
1 2
0 0 

What is the root cause of this ? I worked for a while, but I haven't understood yet, if someone has opinion, will you please let me know. thanks

Upvotes: 0

Views: 98

Answers (1)

wohlstad
wohlstad

Reputation: 28299

The problem does not relate to std::cin at all. The problem is the way you used auto in the range based loop.

In order to update the std::vector, you should change:

for(auto x:A) cin>>x;

to:

for(auto & x:A) cin>>x;  // NOTE: added '&'

Because the meaning of auto does not include "reference-ness" (even if the expression assigned to the auto is in fact a reference). See more info here: C++ auto& vs auto. This is the more "formal" description (a bit harder to understand): cppreference.com - auto. The bottom line is that auto will be deduced by the compiler to be int in your case (not int&).

Therefore in your code, x in the loop is getting a copy of the element from A, which is filled by cin (i.e. the vector is not modified).

Same applies to constness. Therefore when you print the std::vector, it's better to do something like:

for(auto const & y:A) cout<<y<<' ';  // NOTE: added 'const &'

This will cause the compiler to ensure that A's elements are not modified in the loop (due to const) and be efficient (using reference [&] will avoid coping the elements).

Some other notes:

  1. Better to avoid #include <bits/stdc++.h> - see here: Why should I not #include <bits/stdc++.h>?.
  2. Better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.

Upvotes: 4

Related Questions