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;
}
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.