我正在尝试创建一个函数,该函数将读取两个输入字符串并确定它们是否是彼此的字谜(换句话说,如果字符串长度相同并且包含相同数量和类型的字符,则该函数将返回 true )。我尝试使用嵌套 for 循环来实现此目的,但生成了一个错误:“libc++abi:由于未捕获类型 std::out_of_range: basic_string 的异常而终止”。
我认为这意味着我的一个 for 循环正在尝试利用我的字符串之一中不存在的索引,但我不完全确定为什么会出现这种情况。
这是我迄今为止的代码:
bool isAnagram(string firstString="", string secondString="") {
//Initialize variables.
cin >> firstString >> secondString;
string copySecondString = secondString;
int matchedChars = 0;
//Check if string lengths are equal
if (firstString.size() != secondString.size()) {
return false;
}
// Outer for loop iterates through each character in firstString
// Inner while loop iterates through each character in copySecondString
for (int i = 0; i < firstString.size(); i++) {
for (int copyIndex = 0; copyIndex < copySecondString.size(); copyIndex += 1) {
//Check if index of copySecondString matches i
if (firstString.at(i) == copySecondString.at(copyIndex)) {
matchedChars += 1;
copySecondString.erase(copySecondString.at(copyIndex));
cout << copySecondString.size();
break;
}
}
}
if (matchedChars == firstString.size()) {
return true;
}
}
现在,我确信这在某种程度上看起来相当业余且效率低下,这是一个公平的评估,因为我刚刚开始编码。我并没有纠正我的整个方法(我可能会在以后的单独问题中寻求帮助),而是只是试图找出为什么编写的代码失败了。我怀疑这个问题与我的内部 for 循环有关,因为我最终(我认为)从循环表达式中引用的字符串中删除了字符,也许这会导致 copyIndex 超过 copySecondString 的长度。但我实际上并不“知道”这一点,因为我无法完全理解我脑海中发生的事情。谁能指出为什么会出错?
[]
。
.at
函数是不必要的,因为 for 循环在每次传递后都会自动递增,因此方括号可以完成这项工作。您的
erase
函数从 copySecondString
字符串中删除元素,从而缩短数组大小。但copyIndex不断增加,导致copySecondString
中的字符被跳过,并且copyIndex
超出了copySecondString
的最大大小,从而导致弹出out_of_range
错误消息。这是更正后的版本
bool isAnagram() {
//Initialize variables within the function, unless the values are parsed from other components of your code
String firstString, secondString
cin >> firstString >> secondString;
string copySecondString = secondString;
int matchedChars = 0;
//Check if string lengths are equal
if (firstString.size() != secondString.size()) {
return false;
}
// Outer for loop iterates through each character in firstString
// Inner while loop iterates through each character in copySecondString
for (int i = 0; i < firstString.size(); i++) {
for (int copyIndex = 0; copyIndex < copySecondString.size(); copyIndex++) {
//Check if index of copySecondString matches i
if (firstString[i] == copySecondString[copyIndex]) {
matchedChars ++;
cout << copySecondString.size() - copyIndex;
//this outputs the same value as copySecondString.erase
break;
}
}
}
if (matchedChars == firstString.size()) {
return true;
}
}