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 const
ness. 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:
- Better to avoid
#include <bits/stdc++.h>
- see here: Why should I not #include <bits/stdc++.h>?.
- Better to avoid
using namespace std
- see here Why is "using namespace std;" considered bad practice?.