向量迭代循环抛出错误? [英] vector iteration loop throwing an error?

查看:48
本文介绍了向量迭代循环抛出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

错误:请求从'std :: vector :: const_iterator {aka __gnu_cxx :: __ normal_iterator>}'转换为非标量类型'std :: vector :: iterator {aka __gnu_cxx :: __ normal_iterator>}'

error: conversion from 'std::vector::const_iterator {aka __gnu_cxx::__normal_iterator >}' to non-scalar type 'std::vector::iterator {aka __gnu_cxx::__normal_iterator >}' requested

这是怎么回事?

推荐答案

您所处的环境是 v const .改用 const_iterator .

You are in a context where v is const. Use const_iterator instead.

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

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

Note 1. auto would do this automatically for you:

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

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

Note 2. You could use a range based loop if you don't need access to the iterators themselves, but to the elements of the container:

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

这篇关于向量迭代循环抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆