测试我的代码时出现此奇怪的错误

时间:2020-10-06 19:56:49

标签: c++ string algorithm substr function-definition

我正在codewars.com上执行练习任务,我已经完成了代码并对其进行了测试。它起作用了,所以我尝试上交它,但是随后抛出了2种情况,我的代码不起作用。我想纠正错误,但我不明白错误/尝试失败的含义。

这是错误的图片: enter image description here

这是错误消息:

 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)

如果这完全有问题,这是我的代码: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;
    }
}

这也是我必须要做的任务:

完成解决方案,以便如果传入的第一个参数(字符串)以第二个参数(也是字符串)结尾,则返回true。

请帮助我找出这里的问题,谢谢!

2 个答案:

答案 0 :(得分:3)

通常,字符串str的大小可以小于字符串ending的大小。

因此,变量dif的值可以为负

long long dif = size - end;

在成员函数substr的调用中使用

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

由于该函数的第一个参数的类型为std::string::size_type,这是无符号整数类型,因此使用通常的算术转换将其转换为大的无符号整数值。

可以按照以下演示程序中所示的方式编写该函数。

#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;
}

程序输出为

true
false

答案 1 :(得分:0)

我认为您需要切换end = ending.size()size = str.size();