How to read N integers into a vector?

  • A+
Category:Languages

If I want to read all integers from standard input to a vector, I can use the handy:

vector<int> v{istream_iterator<int>(cin), istream_iterator()}; 

But let's assume I only want to read n integers. Is the hand-typed loop everything I got?

vector<int> v(n); for(vector<int>::size_type i = 0; i < n; i++)     cin >> v[i]; 

Or is there any more right-handed way to do this?

 


As given in comments, copy_n is unsafe for this job, but you can use copy_if with mutable lambda:

#include <iterator> #include <vector> #include <iostream> #include <algorithm>  int main(){     const int N = 10;     std::vector<int> v;     //optionally v.reserve(N);     std::copy_if(         std::istream_iterator<int>(std::cin),         std::istream_iterator<int>(),          std::back_inserter(v),          [count=N] (int)  mutable {             return --count;     });      return 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: