Can i use cin directly inside push_back() in vector in c++

#include
#include
int main()
{
int input, i;
using namespace std;
vector ankit;

for( i = 0;i <4;i++)
	ankit.push_back(cin >> input);

cout << "Output of begin and end: "; 
for (auto i = ankit.begin(); i != ankit.end(); ++i) 
    cout << *i << " "

}

You can always do

vector< int> vec;
FOR(i,0,n){ cin >> x; vec.push_back(x);}

2 Likes

cin always requires a temporary variable to read into, which is ugly: I don’t usually use cin directly - I always wrap it in a helper called read.

With read in place, I usually read my vectors in like this: CodeChef: Practical coding for everyone - not sure if that’s the kind of thing you mean :slight_smile:

1 Like

can’t we do it in above way as it would help us to save creating memory for variable input

I dont know about that, but cin takes very little memory space. It is almost equal to null, and just for 1 cin, you will never get a memory limit exceeded if you want to say that. My preferred way is the way @nuttela has shown

1 Like

cin >> X returns the istream object, so, no. You can however write a function that first reads into a variable then return it’s value as an lvalue. You can then use this function as a template during programming competitions. I have seen @ssjgz doing that, he uses a function read_input or something like that.

1 Like

This is what I do :

vector<int> A(N);
for(auto &i : A)
    cin >> i;
8 Likes

Nice one :thinking: :thinking:

vector v(n,0);
for(int &x:v)
scanf("%d",&x);

Is this really needs ?