c++ - 为每个循环将迭代器分配给 std::vector 的当前元素

标签 c++ vector foreach iterator

我有一个 for each 循环,循环遍历 vector 中的每个元素,对于循环的每次迭代,我希望能够启动一个从当前元素开始的迭代器。我试过了

// TypeVect is a std::vector of type Type
for (Type &element : TypeVect)
{
    std::vector<Type>::iterator it;
    it = &element;
    // ...
}

假设迭代器将分配给当前元素的地址,但我收到错误:

no operator = matches these operands ... Type *

我不知道问题出在哪里。有什么建议么?我可以使用索引处理我的问题,但我只是对这种特殊情况感到好奇。

最佳答案

之所以存在基于范围的循环语法,是因为它简化了遍历范围/容器/跨度恰好一次的琐碎循环。

您的预期循环非常重要。使用基于范围的语法编写该循环会比老式索引或基于迭代器的循环更复杂。这违背了使用基于范围的循环的目的。

就是说,如果我们允许自己犯傻,就有可能在基于范围的循环中获取迭代器:

std::vector<Type>::iterator it = TypeVect.begin() + (&element - TypeVect.data());

assuming that the iterator would be assigned to the address of the current element, but I am receiving the error "no operator = matches these operands ... Type *" and I cannot figure out what the problem is.

你的假设是错误的。您不能将元素的地址分配给类型为 std::vector<Type>::iterator 的变量.问题在于指针与迭代器的类型不同,并且不可转换。

关于c++ - 为每个循环将迭代器分配给 std::vector 的当前元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37971199/

相关文章:

c++ - 将 klib 的 knetfile.c|h 移植到 Windows,当我在 "windows unistd.h"中子时,我得到错误 C2036 : 'void *' : unknown size

c++ - 通过引用返回局部变量

c++ - 错误 : no matching function for call to ‘std::vector<std::__cxx11::basic_string<char>>::push_back(int&)’

php - 有没有办法在 PHP 的 foreach 循环中以特定值开始?

PHP foreach 复制输出数据的最后一次迭代

c++ - segmentation 故障的常见原因的明确列表

c++ - 是否有一种自动合并 C++ 实现(.cpp)和头文件(.h)文件的方法

c++ - 如何在 wxWidgets 的同一窗口中拖放文件和文本?

c++ - 返回 vector 堆栈引用时出现问题

php - 将数组值存储在单独的行中