Is there a C++ analogue to the python idiom:
for i, v in enumerate(listVar):
i.e. I want to iterate with access to both the index and the value of the container I'm iterating over.
You can do it the following way. Let assume that the container is std::vector<int> v
Then you can write something as
std::vector<int>::size_type i = 0;
for ( int x : v )
{
// using x;
// using v[i];
++i;
}
For example
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int>::size_type i = 0;
for ( int x : v )
{
std::cout << x << " is " << v[i] << std::endl;
++i;
}
}
However there is a problem that the iterator shall be a random access iterator. Otherwise you may not use the subscript operator.
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