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?
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 << " ";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With