Setting vector elements in range-based for loop

后端 未结 4 1205
南旧
南旧 2020-11-28 16:50

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

相关标签:
4条回答
  • 2020-11-28 17:13

    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.

    0 讨论(0)
  • 2020-11-28 17:19

    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.

    0 讨论(0)
  • 2020-11-28 17:22

    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.

    0 讨论(0)
  • 2020-11-28 17:30

    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.

    0 讨论(0)
提交回复
热议问题