Getting input directly into a vector in C++

前端 未结 5 1610
无人共我
无人共我 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 values(N);
    for (vector::iterator iter = values.begin(); iter != values.end(); ++iter)
    {
      std::cin >> *iter;
    }
    

提交回复
热议问题