c++ - 在基于范围的 for 循环中设置 vector 元素

标签 c++ c++11

<分区>

在分配给动态分配的元素时,我遇到了我认为 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在读取功能中,一切都按照我的预期进行。

我错过了什么?

最佳答案

改变这个循环语句

for(auto n: *CTdata)

for(auto &n : *CTdata)

也就是说,您必须使用对 vector 元素的引用。

关于c++ - 在基于范围的 for 循环中设置 vector 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56079786/

相关文章:

c++11 - std::future 和 clang 与 -stdlib=libstdc++

C++ 异步线程在调用线程完成时终止

c++ - 抽象类和对象

c++无法输出unicode字符,即使我可以直接编写它们

c++ - printf 比 std::cout 快 5 倍以上?

algorithm - 向量中的最小值,跳过一些索引

c++ - 使用 lambda 迭代 std::vector 不想使用 remove_if 删除

c++ - 此代码如何在不重载赋值运算符的情况下运行

c++ - 使用可变参数模板创建静态数组

c++ - 如何创建一个数组来保存要在模板函数中迭代使用的 C++ 类(而非实例)