I have a function that looks like this:
void myclass::myfunc()
{
int i;
for( std::vector<Foo>::iterator it = var.begin(), i = 0; it < var.end(); it++, i++ )
{
/* ... */
}
}
I'm getting this error:
Cannot convert from
int
tostd::_Vector_iterator<>
What is wrong with this code?
Yes, it is, there is no restriction about it. In C++ is also very common creating for loops with iterators. Show activity on this post. This is legal in C and C++ but might not have the behavior you expect unless you understand floating-point and use it properly.
Define an integer outside of the loop, and increment it inside of your loop. Use a for loop instead of foreach, which has a count for you: for(int i = 0; i < array. length; i++) { var item = array[i]; Console.
An iterator provides a number of operations for traversing and accessing data. An iterator may wrap any datastructure like array. An iterator may be thread safe while a for loop alone cannot be as it is accessing elements directly.
The issue is with this part of the for
loop:
std::vector<Foo>::iterator it = var.begin(), i = 0
C++ is interpreting this not as two comma-separated statements, but as a variable declaration for a variable named it
that's an iterator, and as a new declaration of a variable i
that's an iterator and initialized to 0. The error is because you can't initialize a vector
iterator to 0.
To fix this, you'll need to hoist the definition outside of the loop:
int i = 0;
std::vector<Foo>::iterator it = var.begin();
for(; it < var.end(); it++, i++ )
{
// ...
}
Or move the initialization of i
outside the loop:
int i = 0;
for( std::vector<Foo>::iterator it = var.begin(); it < var.end(); it++, i++ )
{
// ...
}
Here's another option. If you need to keep track of the index into the vector you're currently looking at, you could consider just using a counting for loop (without the iterator), or using just the iterator and using iterator subtraction to recover the index:
for (auto it = var.begin(); it != var.end(); ++it) {
// current position is it - var.begin();
}
And, finally, if you have a C++20-compliant compiler, you could eliminate the iterator entirely and use an enhanced for
loop in the following way:
/* Requires C++20 */
for (int i = 0; Foo f: var) {
/* Do something worthwhile with f. */
i++;
}
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With