Search code examples
c++vectorpalindrome

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)


Solution

  • It is highly recommended if you learn how to use algorithms delivered by standard library:

    template <typename T>
    bool is_palindrome(const T& container)
    {
        return std::equal(std::begin(container),
            std::begin(container) + std::size(container) / 2,
            std::rbegin(container));
    }
    

    Live test