【发布时间】: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*)&indices[0], sizeof(int) * index_count);这样的东西应该可以解决问题。 -
你应该使用
resize而不是reserve -
@Retired:哎呀,好收获。