Get index of current element in C++ range-based for-loop
Assuming str
is a std::string
or other object with contiguous storage:
std::cin >> str;
for (char& c : str)
if (c == 'b') v.push_back(&c - &str[0]);
Maybe it's enough to have a variable i
?
unsigned i = 0;
for ( char c : str ) {
if ( c == 'b' ) vector.push_back(i);
++i;
}
That way you don't have to change the range-based loop.
The range loop will not give you the index. It is meant to abstract away such concepts, and just let you iterate through the collection.