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