Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of current element in C++ range-based for-loop

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?

like image 448
Shane Hsu Avatar asked Mar 01 '13 02:03

Shane Hsu


People also ask

What is loop index in 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.

What is loop index in C?

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)

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.


3 Answers

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.

like image 110
Daniel Frey Avatar answered Oct 11 '22 01:10

Daniel Frey


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]);
like image 38
Benjamin Lindley Avatar answered Oct 11 '22 01:10

Benjamin Lindley


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.

like image 8
Karthik T Avatar answered Oct 11 '22 02:10

Karthik T