简体   繁体   中英

Eclipse CDT ranged for

I'm trying to write an answer to an exercise in the C++ Primer. Here is my code:

int main()
{
vector<int> v1;
vector<int> v2(10);
vector<int> v3(10, 42);
vector<int> v4{10};
vector<int> v5{10, 42};
vector<string> v6{10};
vector<string> v7{10, "hi"};

for(auto i : v2)
    cout << v2[i] << " " <<;

return 0;
}

The problem is that I'm getting a generic "syntax error" at the for loop. I've tried all combinations of declaring i as int and declaring &i , but no luck. The book made a similar for loop like so:

vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};
for (auto &i : v)
    i *= i;
for (auto i : v)
    cout << i << " ";
cout << endl;

What am I doing that's different?

you misunderstood how the loop works. i is not the index. i contains a copy of the current element of the vector. just try:

for(auto i : v2)
    cout << i << " " <<;

and if you want to modify the content of your vector you should take the element by reference:

for(auto& i : v2)
{
    ++i;
    cout << i << " " <<;
}   

Edit: what compiler are you using? if it´s mingw you will have to enable c++11 features with -std=c++11

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