c++ - "iterator cannot be defined in the current scope"错误

标签 c++ for-loop iterator initialization unordered-set

我是一名新手 C++ 程序员,正在解决一个简单的问题,将名称和分数对一起打印出来。在这里,我使用了 std::unordered_set 作为名称,使用 vector 作为分数(接受重复的分数,但不接受名称),效果很好。

但是有一件事让我对结果感到困惑,那就是如果我尝试在 for 循环中初始化迭代器,编译器会给出一个错误,指出

the iterator "cannot be defined in the current scope."

这给出了错误:

for (int i = 0, std::unordered_set<std::string>::iterator it = names.begin();
                                                i < names.size(); i++, it++)
{
    std::cout << *it << ", " << scores[i] << '\n';
}

但是移到循环之外,它工作正常:

std::unordered_set<std::string>::iterator it = names.begin();
for (int i = 0; i < names.size(); i++, it++)
{
    std::cout << *it << ", " << scores[i] << '\n';
}

为什么迭代器必须在循环外初始化?抱歉,这个简单的问题,我在其他地方搜索过,但没有找到明确的答案。

最佳答案

在 C++ 中 for-loop

for ( declaration-or-expression(optional) ; declaration-or-expression(optional) ; expression(optional) )
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

init-statement

  • either an expression statement (which may be a null statement ";")
  • a simple declaration, typically a declaration of a loop counter variable with initializer, but it may declare arbitrary many variables Note that any init-statement must end with a semicolon ;, which is why it is often described informally as an expression or a declaration followed by a semicolon.

因此,您可以声明相同类型的变量;例如:

for (int i = 0, j = 1; ... ; i++, j++) {...}
     ^^^^^^^^^^^^^^^^

初始化您之前声明的任何类型的变量。例如

std::unordered_set<std::string>::iterator it;
int i;
for (it = names.begin(),  i = 0; i < names.size(); i++, it++) { ... }
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^

因此,您的尝试失败了。

关于c++ - "iterator cannot be defined in the current scope"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68646980/

相关文章:

python - 嵌套变量创建

c++ - 二进制 == : no operator found which takes a left hand operand; vector; iterator

python - Pandas - 在数据框中添加一个标志列

c++ - Boost Asio 编译库出错

c++ - rcpp 函数中的清理时间较长

javascript - 我疯了还是本地存储......?

function - 无法从通用元素的迭代器构建通用类型

c++ - mfc richedit2格式化

c++ - 当没有为类定义复制构造函数时,是否会发生 RVO 优化?

php - 如何使用可变变量 PHP 在 for 循环中使用 SELECT 创建字符串