vector iteration loop throwing an error?

2019-02-24 06:48发布

问题:

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?

回答1:

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


标签: c++ vector