Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing_back value in std::vector without auxiliary variable

Tags:

c++

c++11

I'm wondering if it's possible to push_back a variable into a std::vector without the use of another variable. For quite some time I've been doing this:

std::vector<int> v;

int temp;
std::cin >> temp;
v.push_back(temp);

I was wondering if it was possible to do the same in a single line:

v.push_back(READING_HERE);
like image 760
ajecc Avatar asked Jan 01 '26 10:01

ajecc


1 Answers

Sure, but I doubt it's worth the trouble:

std::copy_n(std::istream_iterator<int>(std::cin), 1, std::back_inserter(v));

std::istream_iterator creates a wrapper iterator around std::cin, which can be used to read the values from std::cin. The 1 is the amount of elements, and then it inserts the value into the vector again.

As mentioned by @T.C., you can even use the following line, which is even shorter:

v.push_back(*std::istream_iterator<int>(std::cin));
like image 199
Rakete1111 Avatar answered Jan 04 '26 03:01

Rakete1111



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!