在基于范围的for循环中设置矢量元素 [英] Setting vector elements in range-based for loop

查看:91
本文介绍了在基于范围的for循环中设置矢量元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在分配给动态分配的 std :: vector 的元素时,遇到了我认为基于c ++ 11范围的for循环很奇怪的行为。我有以下代码:

I have come across what I consider weird behaviour with the c++11 range-based for loop when assigning to elements of a dynamically allocated std::vector. I have the following code:

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; at(i)代替& n 在读取功能中,事情按预期执行。

If I change the loop to a more traditional for(int i=0; i<arraySize; i++) and use &CTdata->at(i) in place of &n in the read function, things do as I would expect.

我缺少什么?

推荐答案

更改此循环语句

for(auto n: *CTdata)

for(auto &n : *CTdata)

那是您必须使用对向量元素的引用。

that is you have to use references to elements of the vector.

这篇关于在基于范围的for循环中设置矢量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆