简体   繁体   English

Eclipse CDT的范围是

[英]Eclipse CDT ranged for

I'm trying to write an answer to an exercise in the C++ Primer. 我正在尝试为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. 问题是我在for循环中收到一个通用的“语法错误”。 I've tried all combinations of declaring i as int and declaring &i , but no luck. 我尝试了将i声明为int并声明&i所有组合,但是没有运气。 The book made a similar for loop like so: 这本书做了类似的for循环,如下所示:

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 如果是mingw,则必须使用-std = c ++ 11启用c ++ 11功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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