Setting vector elements in range-based for loop
c++, c++11
Solution
Change this loop statement
for(auto n: *CTdata)
to
for(auto &n : *CTdata)
that is you have to use references to elements of the vector.
Problem
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; } ``` 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. What am I missing?