I have three questions regarding a homework assignment for C++. The goal was to create a simple palindrome method. Here is my template for that:
#ifndef PALINDROME_H
#define PALINDROME_H
#include <vector>
#include <iostream>
#include <cmath>
template <class T>
static bool palindrome(const std::vector<T> &input)
{
std::vector<T>::const_iterator it = input.begin();
std::vector<T>::const_reverse_iterator rit = input.rbegin();
for (int i = 0; i < input.size()/2; i++, it++, rit++)
{
if (!(*it == *rit)) {
return false;
}
}
return true;
}
template <class T>
static void showVector(const std::vector<T> &input)
{
for (std::vector<T>::const_iterator it = input.begin(); it != input.end(); it++) {
std::cout << *it << " ";
}
}
#endif
Regarding the above code, can you have more than one iterator declared in the first part of the for loop? I tried defining both the “it” and “rit” in the palindrome() method, and I kept on getting an error about needing a “,” before rit. But when I cut and paste outside the for loop, no errors from the compiler. (I’m using VS 2008).
Second question, I pretty much just brain farted on this one. But is the way I have my return statements in the palindrome() method ok? In my head, I think it works like, once the *it and *rit do not equal each other, then the function returns false, and the method exits at this point. Otherwise if it goes all the way through the for loop, then it returns true at the end. I totally brain farted on how return statements work in if blocks and I tried looking up a good example in my book and I couldn’t find one.
Finally, I get this warnings:
\palindrome.h(14) : warning C4018: '<' : signed/unsigned mismatch
Now is that because I run my for loop until (i < input.size()/2) and the compiler is telling me that input can be negative? Thanks!
Yes, but they both have to be of the same type, so you can’t declare both a
const_iteratorand aconst_reverse_iterator.Yes, though why not just compare
*it != *rit?iis signed;std::vector::size()returns an unsigned value. Ifiwas unsigned, you would not get this warning.As a suggestion, though: it might be simpler to use two forward iterators. Initialize one to
.begin()and the other to.end() - 1. You can then increment the first and decrement the second and your loop test simply becomesit1 < it2. Something like the following (completely untested) for-loop:This way you no longer need the separate
icounter and comparisons; everything is done with iterators.