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

Time:10-26

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];

CodePudding user response:

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.

CodePudding user response:

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));

CodePudding user response:

How to emplace_back (append) in vector without declaring variables?

Since you know the size of the vector, you can make use of range based for- loop (Since ) as follows for the vector with n default initialized elements.

// allocate and initialize n number of elements
std::vector<int> vec(n); 
for(int& ele: vec)       // int& for the reference
    std::cin >> ele
  • Related