Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Detect if a vector is a palindrome in C++

I set myself a challenge of trying to make a program that detects if a given vector is a palindrome. Here is the code:

#include <iostream>
#include <vector>

bool isPalindromeArray(std::vector<int>& nums) {
    float size = nums.size()/2;
    int k = 0;

    if(size = int(size)) {
        for(int i = 0; i < size; i++) {
            if(nums[i] == nums[nums.size() - i]) {
                k++;
                if(k == size) {
                    return true;
                }
            }
        }
    } else {
        for(int i = 0; i < int(size) - 1 ; i++) {
            if(nums[i] == nums[(int(size) - 1) - i]) {
                k++;
                if(k == int(size) - 1) {
                    return true;
                }
            }
        }
    }
    return false;
}

int main() {
    std::vector<int> arr;
    arr.push_back(1);
    arr.push_back(2);
    arr.push_back(3);
    arr.push_back(2);
    arr.push_back(1);

    if(isPalindromeArray(arr)) {
        std::cout << "My Code Works";
    }
}

When I run the code, it returns false no matter if the vector has an odd or even number of values. I have tried various troubleshooting steps but I can’t seem to make it work.

(MinGW64, Windows 10, VS Code)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The behaviour of the following line is undefined by the C++ standard:

if (nums[i] == nums[nums.size() - i])

..as the vector subscript is out of range because:

nums[nums.size() - i]

..which, for the first loop, means:

nums[5]

..which is definitely out of range. So just add a -1 to nums.size() - i:

nums[nums.size() - i - 1]

This will print out "My Code Works" (i.e., return true) when a std::vector is palindrome.

Also, this will be a shorter and better version of your code:

bool isPalindromeArray(std::vector<int>& nums) {
    int size = nums.size() / 2;

    for (int i = 0; i < size; i++) {
        if (nums[i] != nums[nums.size() - i - 1]) {
            return false;
        }
    }
    return true;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading