Getting input directly into a vector in C++

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

    Assuming you have already read the initial N, there is a nice trick using istream_iterator:

    std::vector nums;
    nums.reserve(N);
    std::copy(std::istream_iterator(std::cin), 
              std::istream_iterator(),
              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.

提交回复
热议问题