0

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

Heisenberg
  • 4,787
  • 9
  • 47
  • 76
  • 3
    https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h – user438383 May 05 '22 at 09:53
  • 4
    `auto x` >> `auto& x` . `cin` is "work"ing fine. You're just discarding all the values you're reading; one at a time. – WhozCraig May 05 '22 at 09:55
  • 4
    While you don't use it, macros like `REP` doesn't do anything good for your code. It doesn't make it quicker, it doesn't make it easier to read and understand. Shortcut-macros like that is only taught by people and places that arean't mean to be teaching programming. – Some programmer dude May 05 '22 at 09:57
  • please do not include bits/stdc++, its never needed and will not work on some platforms – pm100 May 06 '22 at 04:37

1 Answers1

4

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?.
wohlstad
  • 12,661
  • 10
  • 26
  • 39