can you use Insert 开发者_开发知识库Iterators
while reading from a file to put the data into STL container?
for example:
FILE *stream;
fread(back_inserter(std::list), sizeof(int), 1, stream);
C++ streams are not compatible with C stdio streams. In other words, you can't use C++ iterators with FILE*
or fread
. However, if you use the C++ std::fstream
facilities along with istream_iterator
, you can use an insertion iterator to insert into a C++ container.
Assuming you have an input file "input.txt" which contains ASCII text numbers separated by whitespace, you can do:
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
int main()
{
std::ifstream ifs("input.txt");
std::vector<int> vec;
// read in the numbers from disk
std::copy(std::istream_iterator<int>(ifs), std::istream_iterator<int>(), std::back_inserter(vec));
// now output the integers
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));
}
no you can't. And it's fundamentally not-portable to store int like that. Your code will break if you write your file with a big-endian machine and try to read it with a little-endian machine.
But nobody prevents you to. Just define your own forward iterator that reads binary from a istream. You will likely want to stop using FILE and fread/fopen/fclose function as they are from C era.
then you will be able to write :
std::copy_n(your_custom_forward_iterator, count, back_inserter<std::list<....> >);
精彩评论