【问题标题】:How I should to catch out_of_range exceptions?我应该如何捕捉 out_of_range 异常?
【发布时间】:2020-02-13 09:03:18
【问题描述】:

我的代码中有 out_of_range。我必须如何解决这个问题?有2个功能。第一个函数检查一个字符串是否是回文。第二个函数必须从向量中找到回文并将其复制到一个新的向量中,该向量是一个返回值。

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

}

【问题讨论】:

  • std::vector&lt;std::string&gt; pol 是一个零长度向量。显然,任何使用at 方法的索引都会引发out_of_range 错误。
  • 旁白:如果你使用rbegin()rend()成员,你不要复制字符串:bool IsPalindrome(string a) { return std::equal(a.begin(), a.end(), a.rbegin(), a.rend()); }
  • 旁白2:for (string word : words)

标签: c++ pointers stdvector palindrome indexoutofrangeexception


【解决方案1】:

您正在访问超出循环范围的words。还有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;

【讨论】:

    【解决方案2】:

    您可以使用try catch 块捕获异常:

    try{
    PalindromFilter(a, 2);
    }
    catch(const std::out_of_range& e){
      //std::cout <<"Error: "  << e.what(); //to print the exception description
      //or do whatever
    }
    

    但是,这并不能使您的程序正常运行,您需要解决您的Palindrome 方法问题。

    在您的for 循环中,在最后一次迭代中,您的words 向量访问是out_of_bounds。使用&lt; 而不是&lt;=

    这个:pol.at(i) = words.at(i); 无效,pol.at(i) 在为其分配内存之前不存在,您可以使用vector push_back() 方法,pol.push_back(words[i]);

    【讨论】:

    • @Leeker,不客气,如果您觉得任何答案都满足您的问题,您应该accept it
    猜你喜欢
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 2013-03-29
    相关资源
    最近更新 更多