This is the first time I am using decltype, and I am not quite sure whether I am using it right. The code does compile and seems to work for POD like char and int.
I am, however, wondering whether I might run into any problems with more complex data types - I have been warned by others that things like auto and decltype can quickly get unintended results.
My assumption is that this template would work for any type T that has the operator!= defined. Are there any fringe cases I should be concerned about?
#include <forward_list>
#include <iostream>
#include <cstdlib>
#include <vector>
template<typename T>
bool isPalindrome(const std::forward_list<T>& lf)
{
auto iter = lf.begin();
std::vector<decltype(iter)> bv; // <-- Correct usage?
while(iter!= lf.end())
{ bv.push_back(iter++); }
int istop = bv.size()/2 + bv.size()%2;
iter = lf.begin();
for(int i = bv.size()-1; i>=istop; i--, iter++)
{ if( *iter != *(bv[i])) return false; }
return true;
}
int main(int argc, char* argv[])
{
std::forward_list<int> list = {0,1,2,1,0};
std::cout << "Is palindrome: " << isPalindrome(list) << std::endl;
return 1;
}
Aucun commentaire:
Enregistrer un commentaire