简体   繁体   English

如何修复“断言'__pos <= size'失败”错误?

[英]How to fix “Assertion '__pos <= size' failed” error?

I'm trying to write a function that compares two strings, say, s1 and s2 , and if at some position, s1[i] == s2[i] , then it must increase a counter by one (ie it counts the number of cases which at the same position (say, i ), they contain the same characters).我正在尝试编写一个函数来比较两个字符串,比如s1s2 ,如果在某个位置, s1[i] == s2[i] ,那么它必须将计数器加一(即它计算数字在相同位置(例如i )的情况下,它们包含相同的字符)。

The code I'm using:我正在使用的代码:

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

If the size of the first string is greater than the size of the second one (ie s1.size() > s2.size() ), I get the error below:如果第一个字符串的大小大于第二个字符串的大小(即s1.size() > 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)

What should I do now?我现在该怎么办?

Take the bar as length of smaller string:-将条形作为较小字符串的长度:-

  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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM