سؤال

template<typename T>
bool Palindrome(vector<T> word) {
vector<T>::iterator start = word.begin();
vector<T>::iterator end = word.end();
for (;start != (word.begin() + word.end())/ 2;start++) {
    if (*start != *(--end)) {
        return false;
    }
}
return true;
}

I cannot create iterator of as in line 3 of code. I have to make a palindrome checker for any data type. Is there problem regarding the syntax or we cannot do it this way. Thanks!

The error message is as follows:

'end' was not declared in this scope 'start' was not declared in this scope
dependent-name 'std::vector::iterator' is parsed as a non-type, but instantiation yields a type
dependent-name 'std::vector::iterator' is parsed as a non-type, but instantiation yields a type expected ';' before 'end'
expected ';' before 'start' need 'typename' before 'std::vector::iterator' because 'std::vector' is a dependent scope need 'typename' before 'std::vector::iterator' because 'std::vector' is a dependent scope no match for 'operator/' (operand types are '__gnu_cxx::__normal_iterator >' and 'int')

هل كانت مفيدة؟

المحلول

try the following

template<typename T>
bool Palindrome( const std::vector<T> &word ) 
{
    typename std::vector<T>::const_iterator start = word.begin();
    typename std::vector<T>::const_iterator end   = word.end();

    for ( ; start < word.begin() + word.size() / 2; ++start ) 
    {
        if ( *start != *--end ) return false;
    }

    return true;
}

Here is a test

#include <iostream>
#include <iomanip>
#include <vector>

template<typename T>
bool Palindrome( const std::vector<T> &word ) 
{
    typename std::vector<T>::const_iterator start = word.begin();
    typename std::vector<T>::const_iterator end   = word.end();

    for ( ; start < word.begin() + word.size() / 2; ++start ) 
    {
        if ( *start != *--end ) return false;
    }

    return true;
}

int main() 
{
    std::vector<int> v = { 1, 2, 1 };

    std::cout << std::boolalpha << Palindrome( v ) << std::endl;

    v = { 1, 2, 3 };

    std::cout << std::boolalpha << Palindrome( v ) << std::endl;

    v = { 1, 2, 2, 1 };

    std::cout << std::boolalpha << Palindrome( v ) << std::endl;

    return 0;
}

The output is

true
false
true

نصائح أخرى

Use typename

typename vector<T>::iterator start = word.begin();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top