向量迭代循环抛出错误?

时间:2013-12-04 19:43:16

标签: c++ vector

for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)
  

错误:从'std :: vector :: const_iterator {aka __gnu_cxx :: __ normal_iterator&gt;}'转换为非标量类型'std :: vector :: iterator {aka __gnu_cxx :: __ normal_iterator&gt;}'request < / p>

发生了什么事?

1 个答案:

答案 0 :(得分:12)

您处于vconst的上下文中。请改用const_iterator

for (std::vector<int>::const_iterator it = v.begin(); it != v.end(); ++it)

注意1. auto会自动为您执行此操作:

for (auto it = v.begin(); it != v.end(); ++it)

注意2.如果您不需要访问迭代器本身,而是需要访问容器的元素,则可以使用基于范围的循环:

for (auto elem : v) // elem is a copy. For reference, use auto& elem