how to emplace_back (append) in vector without declaring variables..?

Viewed 152

If number of input are given as first input.
If I need to store them in vector
I can easily do it by creating a variable and using the variable I can append it in the vector
I'm fascinated to know , is there any other way so that I need not have to use a variable..

INPUT

4
1 5 3 2

How vector take inputs

vector<int>vec;
for(int i=0;i<n;i++)
{
    int x;
    cin>>x;    // any idea to remove using a variable here..?
    vec.emplace_back(x);
}

How array takes inputs

int array[n];
for(int i=0;i<n;i++)
cin>>array[i];
2 Answers

Yes, just do this:

std::cin >> vec.emplace_back();

The return type of vector::emplace_back() in C++17 is no longer void. Instead, it returns a reference to the inserted element. So vec.emplace_back() will construct an element by default and return its reference.

Or using STL algorithm (works with C++03):

vector<int> vec;
vec.reserve(n); // good practice to reduce reallocation of memory
std::copy_n(std::istream_iterator<int>{std::cin}, n, std::back_inserter(vec));
Related