【发布时间】:2014-11-22 12:32:40
【问题描述】:
我正在尝试编写一个比较两个字符串的函数,例如,s1 和 s2,如果在某个位置,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() > 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)
我现在该怎么办?
【问题讨论】: