Vector iteration loop throwing an error?

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

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

What's happening?

+4
source share
1 answer

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

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

Note 1. autoWill do this automatically for you:

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

Note 2. You can use a range-based loop if you do not 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
+12
source

All Articles