c++for-loopc++11iteration

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?


Solution

  • 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]);