【问题标题】:std::vector<decltype(iter)> - valid usage of decltype?std::vector<decltype(iter)> - decltype 的有效用法?
【发布时间】:2016-04-01 15:33:00
【问题描述】:

这是我第一次使用decltype,我不太确定我是否正确使用它。该代码确实可以编译,并且似乎适用于 char 和 int 等 POD。

然而,我想知道我是否会遇到更复杂的数据类型的任何问题 - 其他人已经警告我,诸如 auto 和 decltype 之类的东西会很快得到意想不到的结果。

我的假设是这个模板适用于任何定义了 operator!= 的类型 T。有没有我应该关注的边缘案例?

#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;
}

【问题讨论】:

  • 知道这将生成一个迭代器向量,而不是迭代器所指类型的向量。否则,是的,没关系。
  • 在他的代码中他似乎意识到了这一点
  • @OMGtechy :是的,我知道这一点——在我看来这是一个很好的解决方案。我将在 CodeReview 上的一个单独问题中询问这个问题。
  • 首先,您为什么使用forward_list,其次,您为什么关心forward_list 是否是回文?

标签: c++ c++11 decltype


【解决方案1】:

是的,这种用法没有问题。您将使用 std::vectorstd::forward_list::iterator,并且由于这些迭代器满足容器要求,您可以开始了。

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2014-06-12
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多