<分区>
在分配给动态分配的元素时,我遇到了我认为 c++11 基于范围的 for 循环的奇怪行为 std::vector
.我有以下代码:
int arraySize = 1000;
std::string fname = "aFileWithLoadsOfNumbers.bin";
CTdata = new std::vector<short int>(arraySize, 0);
std::ifstream dataInput(fname.c_str(), std::ios::binary);
if(dataInput.is_open()
{
std::cout << "File opened sucessfully" << std::endl;
for(auto n: *CTdata)
{
dataInput.read(reinterpret_cast<char*>(&n), sizeof(short int));
// If I do "cout << n << endl;" here, I get sensible results
}
// However, if I do something like "cout << CTdata->at(500) << endl;" here, I get 0
}
else
{
std::cerr << "Failed to open file." << std::endl;
}
如果我将循环更改为更传统的 for(int i=0; i<arraySize; i++)
并使用 &CTdata->at(i)
代替 &n
在读取功能中,一切都按照我的预期进行。
我错过了什么?