在括号中定义变量

时间:2014-10-23 12:25:06

标签: c++ for-loop scope declaration

我不明白为什么变量i在一开始就不为人所知。 如何在括号中定义变量? (如果用int我这样做我仍然会收到错误)

void cardlike(vector<int> &v)
{
        unsigned max_pos = 0;
        int tmp;
        for (unsigned i = 0; i < v.size(); i++);
        {
                for (unsigned j = 0; j < v.size() - i; j++)
                        if(v[j] > v[max_pos])
                                max_pos = j;

                tmp = v[max_pos];
                v[max_pos] = v[v.size() - i - 1];
                v[v.size() - i - 1] = tmp; 
        }
}

当我用-std = c ++ 11编译它时,这就是我从g ++得到的:

sortvector.cpp:93:38: error: ‘i’ was not declared in this scope   
   for(unsigned j = 0; j < v.size() - i; j++)
                                      ^
sortvector.cpp:98:29: error: ‘i’ was not declared in this scope   
   v[max_pos] = v[v.size() - i - 1];
                             ^

2 个答案:

答案 0 :(得分:10)

for循环

之后,你有一个不必要的半冒号
for (unsigned i = 0; i < v.size(); i++);

删除它

for (unsigned i = 0; i < v.size(); i++)

此外,如果你有一个多行for循环,你真的应该使用{}大括号

for (unsigned j = 0; j < v.size() - i; j++)
                        if(v[j] > v[max_pos])
                                max_pos = j;

for (unsigned j = 0; j < v.size() - i; j++)
{
    if(v[j] > v[max_pos])
        max_pos = j;
}

答案 1 :(得分:1)

在此处删除分号:

        for (unsigned i = 0; i < v.size(); i++)
                                               ^