【问题标题】:I'm getting this weird error when testing my code测试我的代码时出现这个奇怪的错误
【发布时间】:2021-01-21 18:09:00
【问题描述】:

我在 codewars.com 上做一个练习任务,我已经完成了我的代码并对其进行了测试。它起作用了,所以我试图把它交出来,但后来我遇到了两个我的代码不起作用的情况。我想改正我的错误,但我不明白错误/失败尝试的含义。

这是错误的图像:

这是错误信息:

 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。

请帮我找出问题所在,谢谢!

【问题讨论】:

  • 如果endingstr 长怎么办?
  • 仅供参考 - 您无需创建另一个字符串即可查看 str 是否以 ending 结尾。

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    一般情况下,字符串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
    

    【讨论】:

      猜你喜欢
      • 2011-12-16
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多