c++ - 未找到 difference_type

标签 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;
}

给出错误:

/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>’

最佳答案

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

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

关于c++ - 未找到 difference_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13345392/

相关文章:

gcc - gcc -march选项的默认设置是什么?

c++ - 枚举型函数返回错误 "was not declared in this scope"

C++ 和 Windows - NtCreateThreadEx 函数的 DLL 注入(inject)不起作用

c++ - 类的静态实例在程序退出时无法正确处理资源删除

c - 递归main函数分析

c - 为什么我的 "=r"(var) 输出没有选择与 "a"(var) 输入相同的寄存器?

c++ - 如何用 std::set 包含我的类

c++ - 检索函数内用 operator new 分配的类指针对象成员的值的问题

string - fscanf 使用宏固定字符串大小

linux - 如何降低 GCC 中的编译成本和 make?