1

I have a file and want to store first N number of characters in a vector. Currently I read all the characters and just take first N characters.

std::ifstream stream(m_filename, std::ios::in | std::ios::binary);
...
...
// m_header is vector<unsigned cha>
m_header.insert(m_header.begin(),
           std::istream_iterator<unsigned char>(stream),
           std::istream_iterator<unsigned char>()); 

Is there a way to just read N characters using istream_iterator?

Sumit Jha
  • 1,601
  • 11
  • 18

1 Answers1

1

If you really want to use std::istream_iterator, a solution could be:

void foo() {
  std::ifstream stream;
  // open stream

  std::vector<unsigned char> v;

  std::copy_if(std::istream_iterator<unsigned char>(stream),
               std::istream_iterator<unsigned char>(),
               std::back_inserter(v),
               [](unsigned char) {
                 static constexpr int N = 3;
                 static int i = 0;
                 return ++i <= N;
               });
}
BiagioF
  • 9,368
  • 2
  • 26
  • 50