Getting input directly into a vector in C++

前端 未结 5 1558
无人共我
无人共我 2021-01-18 23:59

Consider the following code piece:

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


        
相关标签:
5条回答
  • 2021-01-19 00:08

    No need to allocate the vector and then resize it.

    Iterators are preferable to index usage.

    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 讨论(0)
  • 2021-01-19 00:10

    Assuming you have already read the initial N, there is a nice 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 back_inserter object turns itself into an iterator that adds elements to the vector at the end. Iterator streams can be parameterized by the type of the elements read, and, if no parameter given, signals the end of input.

    0 讨论(0)
  • 2021-01-19 00:19
    vector<int> nums(N);
    for (int i = 0; i < N; i++)
    {
        cin >> nums[i];
    }
    

    In the general case, this is actually more efficient. Calling std::vector::push_back() repeatedly without an initial reserve will lead to lots of reallocations.

    0 讨论(0)
  • 2021-01-19 00:19

    Hinted from Diego Sevilla answer. Use a range constructor

    std::vector<int> nums( std::istream_iterator<int>(std::cin),
                           std::istream_iterator<int>() );
    
    0 讨论(0)
  • 2021-01-19 00:28

    If you don't have already copy_n() in your toolbelt then you should. Very useful.

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

    With this utility it's convenient and elegant to copy n elements into a vector:

    #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());
    
    0 讨论(0)
提交回复
热议问题