简体   繁体   中英

vectors in range based for loop

I was testing vector to vector initialization, I used range based for loop it gives different output.

with respect to Normal for loop.

vector<int> intVector;

for(int i = 0; i < 10; i++) {
    intVector.push_back(i + 1);
    cout << intVector[i] << endl;
}

cout << "anotherVector" << endl;

vector<int> anotherVector(intVector);
for(auto i : anotherVector)
    cout << anotherVector[i] << endl;
//for(unsigned int i = 0; i < anotherVector.size(); i++) {
//    cout << anotherVector[i] << endl;
//}

this range based for loop gives the output - Linux ubuntu

Output

STLTest Cunstructor Called.
1
2
3
4
5
6
7
8
9
10
anotherVector
2
3
4
5
6
7
8
9
10
81

2.

vector<int> intVector;

for(int i = 0; i < 10; i++) {
    intVector.push_back(i + 1);
    cout << intVector[i] << endl;
}

cout << "anotherVector" << endl;

vector<int> anotherVector(intVector);
//for(auto i : anotherVector)
//    cout << anotherVector[i] << endl;
for(unsigned int i = 0; i < anotherVector.size(); i++) {
    cout << anotherVector[i] << endl;
}

This gives different output.

output

STLTest Cunstructor Called.
1
2
3
4
5
6
7
8
9
10
anotherVector
1
2
3
4
5
6
7
8
9
10

why both for loop acting differently?

for(auto i : anotherVector)
    cout << anotherVector[i] << endl;

This code doesn't do what you think it does. The range-based for loop iterates over values, not over indices. In other words, the loop variable ( i ) is assigned all ements of the vector in turn.

To replicate the functionality of your first loop, you need this:

for (auto i : anotherVector)
    cout << i << endl;

What your original code was doing was take an element of the vector, and use it to index into the vector again. That's why the numbers were off by one (since the vector held number n + 1 at position n ). Then, the final output (81 in your case) was effectively random and the result of Undefined Behaviour—you were reaching past the end of the vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM