【问题标题】:Using iterators to read binary integer list from file使用迭代器从文件中读取二进制整数列表
【发布时间】:2026-01-21 22:15:02
【问题描述】:

我正在寻找一种在使用std::ifstream 从文件中读取二进制整数时使用迭代器填充std::vector 容器的方法。

我尝试了以下方法:

std::vector<int> indices;
indices.reserve(index_count);
std::copy(std::istream_iterator<int>(ifstream), std::istream_iterator<int>(), std::back_inserter(indices));

但没有添加任何条目。我读过这个方法可能只适用于字符串?

无论如何,任何建议将不胜感激。 :)

【问题讨论】:

  • 你能澄清一下“二进制整数”是什么意思吗?文件中有原始整数字节吗?
  • @Cameron 是的,原始字节。
  • 啊,那样的话就不需要使用迭代器了。只需复制字节(并注意字节顺序——整数的原始字节不能在所有处理器之间移植)。像indices.reserve(index_count); ifstream.read((char*)&amp;indices[0], sizeof(int) * index_count); 这样的东西应该可以解决问题。
  • 你应该使用resize 而不是reserve
  • @Retired:哎呀,好收获。

标签: c++ file binary iterator


【解决方案1】:

您必须编写自己的迭代器来执行此操作。这样做没有用 - 它会很慢,因为迭代器的每个 ++ 都会进行另一次读取(这是很多读取,或者至少比必须存在的要多得多)。

如果你有一个纯整数的文件...

std::ifstream is("filename.ints", std::ios::binary|std::ios::in);
is.seekg(0, std::ios::end);
auto length = is.tellg();
is.seekg(0)

std::vector<int> ints(length/sizeof(int), 0);
is.read(reinterpret_cast<char*>(ints.data()), ints.size()*sizeof(int));

【讨论】: