Search code examples
c++pointersstdvectorpalindromeindexoutofrangeexception

How I should to catch out_of_range exceptions?


I get out_of_range in my code. How I have to fix this? There are 2 functions. The first function checks a string if it is a palindrome. The second function has to find palindromes from vector and copy it to a new vector which is a return value.

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

}

Solution

  • You can catch an exception with a try catch block:

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

    However this doesn't make your program work as it should, you need to solve your Palindrome method issues.

    In your for loop, in the last iteration, your words vector access is out_of_bounds. Use < instead of <=.

    This: pol.at(i) = words.at(i); is not valid, pol.at(i) doesn't exist until memory is allocated for it, you can use vector push_back() method, pol.push_back(words[i]);