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);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With