C++ 我应该如何发现超出范围的异常?
我的代码超出了范围。我要怎么解决这个问题?有两个功能。第一个函数检查字符串是否为回文。第二个函数必须从向量中找到回文并将其复制到一个新的向量中,该向量是一个返回值C++ 我应该如何发现超出范围的异常?,c++,pointers,stdvector,palindrome,indexoutofrangeexception,C++,Pointers,Stdvector,Palindrome,Indexoutofrangeexception,我的代码超出了范围。我要怎么解决这个问题?有两个功能。第一个函数检查字符串是否为回文。第二个函数必须从向量中找到回文并将其复制到一个新的向量中,该向量是一个返回值 #include "pch.h" #include <iostream> #include <string> #include <algorithm> #include <vector> using namespace std; bool IsPalindrom(string a)
#include "pch.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
bool IsPalindrom(string a)
{
string b = a;
reverse(a.begin(), a.end());
if (b == a)
{
cout << "success " << endl;
return true;
}
else {
cout << "error";
return false;
}
}
vector<string> PalindromFilter(vector<string> words, int minLength)
{
vector<string> pol;
for (int i = 0; i <= words.size(); ++i)
{
if (IsPalindrom(words[i]) && words[i].size() > minLength)
{
pol.at(i) = words.at(i);
}
}
return pol;
}
int main()
{
vector<string> a = { "ama", "madam", "safg", "arnold", "dad", "dd" };
PalindromFilter(a, 2);
}
您正在访问循环中超出范围的单词。pol也是空的,所以您需要使用push_back来添加新元素
vector<string> pol;
for (int i = 0; i < words.size(); ++i)
{
if (IsPalindrom(words[i]) && words[i].size() > minLength)
{
pol.push_back(words.at(i));
}
}
return pol;
您可以使用try-catch块捕获异常: 然而,这并不能使您的程序正常工作,您需要解决回文方法问题
在for循环中,在最后一次迭代中,单词向量访问超出了界限。Use std::vector pol是一个零长度向量。显然,任何使用该方法的索引都会抛出一个超出范围的错误。旁白:如果使用的是rbegin和rend成员,则不需要复制字符串:bool IsPalindromestring a{return std::equala.begin,a.end,a.rbegin,a.rend;}旁白2:对于字符串单词:words@Leeker,不客气,如果你觉得任何答案都能满足你的问题,你应该
try{
PalindromFilter(a, 2);
}
catch(const std::out_of_range& e){
//std::cout <<"Error: " << e.what(); //to print the exception description
//or do whatever
}