Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector iteration loop throwing an error?

Tags:

c++

vector

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 non-scalar type 'std::vector::iterator {aka __gnu_cxx::__normal_iterator >}' requested

What's going on?

like image 657
user111373 Avatar asked Dec 12 '22 09:12

user111373


1 Answers

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)

Note 1. auto would do this automatically for you:

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

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
like image 146
juanchopanza Avatar answered Dec 13 '22 22:12

juanchopanza