Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between foreach(int i.. and foreach(auto i

Tags:

c++

auto

I am experimenting with C++11 features on the Clang compiler that comes with Mac OX (LLVM 4.2) and the following results puzzles me:

// clang compile with "c++ -std=c++11 -stdlib=libc++"
#include <iostream>
#include <vector>
int main(void) {
    using namespace std;
    vector<int> alist={1, 2, 3, 4};

    for (int i=0; i<alist.size(); i++) {
        cout << alist[i] << " ";
    }
    cout << endl;

    for (auto i: alist) {
        cout << alist[i] << " ";
    }
    cout << endl;

    return 0;
}

Pending on the running environment, I am getting different outputs as the following:

1 2 3 4 
2 3 4 0 

Why do I get different results?

like image 646
Oliver Avatar asked Feb 17 '23 00:02

Oliver


1 Answers

for (auto i: alist)

This fetches every value in alist, so i becomes:

1,2,3,4

You then do

cout << alist[i] << " ";

which means alist[1], alist[2], alist[3] and alist[4] and not the values 1, 2, 3, 4. You should simply write :

cout << i << " ";
like image 158
Nbr44 Avatar answered Feb 28 '23 11:02

Nbr44