1

I am solving a problem where I need to return the last index of '1' in a given string. If not present then return -1. I wrote the following simple code, but for input string input "0" it fails. I tried to debug bu using GDB and I noticed that once loop statement of index() function runs once then a garbage value is assigned to iteration variable i.

#include <iostream>
#include <string>
using namespace std;

int index(string &str) {
    int result = -1;
    for(auto i = str.length() - 1; i >= 0; --i) {
        if(str[i] == '1')
            return i;
    }
    return result;
}
int main() {
    int T;
    cin >> T;
    cin.ignore();
    while(T--) {
        string str;
        cin >> str;
        cout << index(str) << endl;
    }
    return 0;
}

What exactly is the problem?

enter image description here Notice the value of i in the second iteration.

Arun Suryan
  • 1,615
  • 1
  • 9
  • 27

1 Answers1

1

Your program has undefined behaviour here:

for(auto i = str.length() - 1; i >= 0; --i) {
    if(str[i] == '1')
        return i;
}

The length() of an std::string has an unsigned type, and since you used auto that means your i is unsigned too (to be precise, a std::size_t).

Such values never go below zero. They wrap around to the maximum value of the type (a very large number!).

So, your loop condition does nothing; it's always true. Instead, out-of-bounds accesses str[i] then occur until one of the unspecified values that results happens to look like '1'. Then, the massive i is returned.

It is possible to loop backwards through a standard container or string, but you have to be careful about it. My recommendation to you is to use iterators; in this case, reverse iterators.

for (auto it = str.rcbegin(); it != str.rcend(); ++it)
{
    if (*it == '1')
        return std::distance(it, str.rcend());
}
Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35
  • I got your point. But for taking `i` as following warning occurs: Narrowing conversion from 'unsigned long' to signed type 'int' is implementation-defined. What is a good way to tackle this? – Arun Suryan Mar 21 '20 at 16:01
  • @ArunSuryan I added a link to some material for you to read. Take your time and study it. – Asteroids With Wings Mar 21 '20 at 16:04