Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any (convenient) way of retrieving current iteration # inside C++11 "foreach" statement?

Tags:

c++

c++11

I'm wondering whether it is possible to somehow extract current iteration number from c++11 foreach statement.

In code like this:

for(auto &i: vect)
    if(i == 0) zero_value_index = /* here I want my index */;

I can't find another way around, but using old-fashioned for with int i to easily obtain my index.

Ideas?

like image 1000
Pearley Avatar asked Mar 19 '23 17:03

Pearley


1 Answers

You could, I don't know, count the iterations:

int i = 0;
for (auto& el : container) {
    if (el == 0) zero_value_index = i;
    ++i;
}
like image 78
Ben Voigt Avatar answered May 06 '23 09:05

Ben Voigt