找不到difference_type

abe*_*ier 8 c++ gcc gcc4.7

当我尝试std::distance在gcc 4.7下使用自定义迭代器时,它抱怨没有找到difference_type.我遗憾地不知道它为什么会失败.

#include <iterator>

class nit {
public:
    typedef int difference_type;
};

int main() {
  const nit test1;
  std::distance( test1, test1 );
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

给出错误:

/usr/include/c++/4.7/bits/stl_iterator_base_funcs.h:114:5: error: no type named ‘difference_type’ in ‘struct std::iterator_traits<nit>’

Jul*_*yer 6

您是否尝试过定义所有必需的类型/运算符?

#include <iterator>

struct nit
{
  typedef std::random_access_iterator_tag iterator_category;
  typedef int value_type;
  typedef int difference_type;
  typedef int* pointer;
  typedef int& reference;

  bool operator==(nit const&)
  {
    return true;
  }

  bool operator!=(nit const&)
  {
    return false;
  }

  int operator-(nit const&)
  {
    return 0;
  }

  nit()
  {
  }
};

int main()
{
  nit const test1;
  std::distance(test1, test1);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)