My code is as follows:
std::cin >> str;
for ( char c : str )
if ( c == 'b' ) vector.push_back(i) //while i is the index of c in str
Is this doable? Or I will have to go with the old-school for loop?
Python For Loop with Index using range() range() function returns an iterable with range of numbers. So, range() function can be used to iterate over the range of indexes of the iterable. Please note that, using range() function, to get index and accessing element using index, is not in the spirit of python.
The index is the variable which you use to to keep track of the iterations of the loop. Generally index variables are integers, but they don't have to be. In this code example - the variable ind is the index variable in the for loop. int my_strcmp(char *first, char *second)
Yes, it is, there is no restriction about it. In C++ is also very common creating for loops with iterators.
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.
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]);
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.
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