Getting input directly into a vector in C++

前端 未结 5 1594
无人共我
无人共我 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:28

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

    template
    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
    #include
    #include
    
    // ...
    int n = 0;
    std::cin >> n;
    std::vector v(n);
    copy_n(std::istream_iterator(std::cin), std::istream_iterator(),
           n,
           v.begin());
    

提交回复
热议问题