문제

I was not sure how to frame the title but the explanation is simpler. I was playing with the c++11 range for loops (link).

I wrote the following:

for(auto &elem:vec){
    elem/=vec[0];
}

Which compiles but does not change anything in the vector 'vec'.

This, on the other hand, works:

elem0 = vec[0];
for(auto &elem:vec){
    elem/=elem0;
}

Is this expected? What is wrong with the first method? If it helps, my compiler version is g++ 4.6.3.

도움이 되었습니까?

해결책

Actually it works just fine except that, in your example, vec[0] has been changed to 1 after the first run, which makes the remaining runs look like "not working" (remain the same value if divided by 1).

You will see it clearly by using the following example (will work "as expected"):

vector<float> vec = { 1, 2, 3, 4, 5 };
for (auto &elem : vec){
    elem /= vec[4];
}

// now vec={0.2, 0.4, 0.6, 0.8, 1.0}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top