Getting input directly into a vector in C ++

Consider the following code snippet:

...
int N,var;
vector<int> nums;
cin >> N;
while (N--)
{
   cin >> var;
   nums.push_back(var);
}
...

Can this be done without using an auxiliary variable, in this case var?

+3
source share
5 answers

Assuming you already read the starter N, there is a good trick using istream_iterator:

std::vector<int> nums;
nums.reserve(N);
std::copy(std::istream_iterator<int>(std::cin), 
          std::istream_iterator<int>(),
          std::back_inserter(nums));

The object back_inserterturns into an iterator, which adds elements to the vector at the end. Iterator streams can be parameterized by the type of read elements, and, if the parameter is not specified, signals the end of the input.

+10
source

copy_n() toolbelt, . .

template<class In, class Size, class Out>
Out copy_n(In first, In last, Size n, Out result)
{
    while( n-- > 0 && first != last )
        *result++ = *first++;
    return result;
}

n :

#include<iterator>
#include<vector>
#include<iostream>

// ...
int n = 0;
std::cin >> n;
std::vector<int> v(n);
copy_n(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
       n,
       v.begin());
+4
vector<int> nums(N);
for (int i = 0; i < N; i++)
{
    cin >> nums[i];
}

. std::vector::push_back() reserve .

+2

.

std::vector<int> nums( std::istream_iterator<int>(std::cin),
                       std::istream_iterator<int>() );
+1

, .

.

size_t N;
std::cin >> N;

std::vector<int> values(N);
for (vector<int>::iterator iter = values.begin(); iter != values.end(); ++iter)
{
  std::cin >> *iter;
}
0

Source: https://habr.com/ru/post/1774826/


All Articles