Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a for loop that uses both an iterator and an index counter?

Tags:

c++

for-loop

stl

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 to std::_Vector_iterator<>

What is wrong with this code?

like image 698
Igor Avatar asked Jun 10 '13 03:06

Igor


People also ask

Can we use a double value as in index in a for loop?

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.

How do I add a counter in foreach loop?

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.

Can we use for loop instead of iterator?

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.


1 Answers

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!

like image 167
templatetypedef Avatar answered Sep 27 '22 03:09

templatetypedef