c++ - 在 for 的括号中定义变量

标签 c++ for-loop scope declaration

<分区>

我不明白为什么变量 i 在整个 first for 中都不知道。 在 for 的括号中定义变量如何工作? (如果用 int i 做,我仍然会出错)

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];
                             ^

最佳答案

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;
}

关于c++ - 在 for 的括号中定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26528037/

相关文章:

c++ - 如何在 Windows 中提及特定字体作为特定 unicode 值的默认字体?

c++ - 如何通过优化查看 C++ 代码的编译器重构

javascript - 使用全局变量来防止代码不必要地重复执行

javascript - 对 JavaScript 变量作用域(单级)有点困惑

php - 更改 PHP 类函数的隐私范围

c++ - std::pair 将 first 和 second 分配给语义命名的变量

c++ - 如何跳出一个C++代码块?

javascript - for循环只输出最后一次迭代

r - 在 R 中循环获取 ChangePoint 数据

没有 for 循环的 R 二进制详尽列表