Warm tip: This article is reproduced from stackoverflow.com, please click
algorithm c++ function-definition string substr

I'm getting this weird error when testing my code

发布于 2021-01-28 16:50:21

I was doing a practise task on codewars.com and I had finished my code and tested it. It worked and so I attempted to hand it in, but then I got thrown 2 cases where my code doesn't work. I wanted fix my mistakes but I don't understand what the error/ failed attempt means.

Here's an image of the error: enter image description here

Here's the error message:

 Sample_Test_Cases
Caught std::exception, what(): basic_string::substr: __pos (which is 18446744073709551615) > this->size() (which is 3)

 Random_Test_Cases
Caught std::exception, what(): basic_string::substr: __pos (which is 18446744073709551614) > this->size() (which is 8)

And here's my code if there's something completely wrong with it :D

bool solution(std::string const &str, std::string const &ending) {
  
  long long end = ending.size(), size = str.size();
  long long dif = size - end;
  string endi = str.substr(dif, end);
  
  if(endi != ending) {
    return false;
  }
  else {
  return true;
    }
}

And also here the task I had to do:

Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).

Please help me figure out whats the problem here, thanks !

Questioner
richiE
Viewed
0
Vlad from Moscow 2020-10-07 04:33

In general the size of the string str can be less than the size of the string ending.

Thus the value of the variable dif can be negative

long long dif = size - end;

Used in the call of the member function substr

string endi = str.substr(dif, end);

it is converted using the usual arithmetic conversions to a big unsigned integer value due to the fact that the first parameter of the function has the type std::string::size_type that is an unsigned integer type.

The function can be written the following way as it is shown in the demonsgtrative program below.

#include <iostream>
#include <iomanip>
#include <string>
#include <iterator>
#include <algorithm>

bool solution( const std::string &str, const std::string &ending )
{
    return !( str.size() < ending.size() ) && 
           std::equal( std::rbegin( ending ), std::rend( ending ), std::rbegin( str ) ); 
}

int main() 
{
    std::string s( "Hello World!" );
    
    std::cout << std::boolalpha << solution( s, "World!" ) << '\n';
    std::cout << std::boolalpha << solution( s, "World" ) << '\n';

    return 0;
}

The program output is

true
false