Getting input directly into a vector in C++

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

    vector 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.

提交回复
热议问题