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 hav
you have to write
for( auto& n : *CTdata )
because auto n
means short int n
when you need short int& n
.
i recommend you to read difference beetween decltype and auto.
Vlad's answer perfectly answers your question.
However, consider this for a moment. Instead of filling your array with zeroes from the beginning, you could call vector<>::reserve()
, which pre allocates your backing buffer without changing the front facing portion of the vector.
You can then call vector<>::push_back()
like normal, with no performance implications, while still maintaining the logic clear in your source code. Coming from a C# background, looping over your vector like that looks like an abomination to me, not to mention you set each element twice. Plus if at any point your element generation fails, you'll have a bunch of zeroes that weren't supposed to be there in the first place.
The reason your loop fails is because you reference vector elements by value. However, in this case you can eliminate the loop altogether:
dataInput.read(reinterpret_cast<char*>(CTdata->data()), arraySize*sizeof(short int));
This reads the content into the vector in a single call.
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.