【问题标题】:How to fix "Assertion '__pos <= size' failed" error?如何修复“断言'__pos <= size'失败”错误?
【发布时间】:2014-11-22 12:32:40
【问题描述】:

我正在尝试编写一个比较两个字符串的函数,例如,s1s2,如果在某个位置,s1[i] == s2[i],那么它必须将计数器加一(即它计算数字相同位置的案例(例如,i),它们包含相同的字符)。

我正在使用的代码:

#include <iostream>
#include <string>

using namespace std;

int posicions_iguals(string s1, string s2)
{
  int count = 0;
  for (int i = 0; i < s1.size(); ++i){
    if (s1[i] == s2[i])
      ++count;
  }
  return count;
}

int main()
{
  string s1;
  string s2;
  while (cin >> s1) {
    cin >> s2;
    cout << posicions_iguals(s1, s2) << endl;
  }
}

如果第一个字符串的大小大于第二个字符串的大小(即s1.size() &gt; s2.size()),我会收到以下错误:

/usr/include/c++/4.8/bits/basic_string.h:846: std::basic_string<_CharT, 
_Traits, _Alloc>::reference std::basic_string<_CharT, _Traits, 
_Alloc>::operator[](std::basic_string<_CharT, _Traits, _Alloc>::size_type) 
[with _CharT = char; _Traits = std::char_traits<char>; _Alloc = 
std::allocator<char>; std::basic_string<_CharT, _Traits, 
_Alloc>::reference = char&; std::basic_string<_CharT, _Traits, 
_Alloc>::size_type = long unsigned int]: Assertion '__pos <= size()' failed.
Aborted (core dumped)

我现在该怎么办?

【问题讨论】:

    标签: c++ string iostream


    【解决方案1】:

    以小节为长度:-

      int count = 0;
      int length = (s1.size() < s2.size()) ? s1.size() : s2.size();
      for (int i = 0; i < length; ++i)
      {
        if (s1[i] == s2[i]) 
          ++count;
      }
      return count;
    

    【讨论】:

    • 你能解释一下这条线的作用吗?
    • 这里的长度将是较小字符串的大小,因此它将在两个字符串的范围内...在您的情况下,如果您考虑到,您可能会越过一个字符串的范围较大字符串的长度。
    • 使用 min() 可能比 (:?) 语法更清晰。
    • @aleixrr - 它是 if-else 块的缩写形式。 x==y?true:false; -> if (x==y) return true; else return false;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2012-11-28
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多