c++ - 迭代器和 const_iterator operator++ post and prefix

标签 c++ iterator operator-overloading prefix-operator

我们正在开发自定义列表类。我们正在尝试实现 iterator 和 const_iterator 及其函数,但我们的++ 运算符存在问题。 PostFix 根本不起作用,而当我们走得太远时,PreFix 会给出段错误(当前代码是一种仅返回最后有效结果的变通方法)。 问题1:我们如何在不返回最后一个有效元素的情况下修复与前缀相关的段错误? (我们已经尝试返回 nullptr)。

Postfix 只是不会迭代,即使我们已经遵循了互联网上的所有指南<.<

问题 2:为什么 PostFix 不起作用?

后缀代码:

List_const_iterator_& operator++()
  {
    if(ptr->next_ != nullptr)
    {
        ptr = ptr->next_;
        return *this;
    }
    else
        return *this;
  }

  List_const_iterator_ operator++(int unused)
  {
    List_const_iterator_ temp(*this);
    if(ptr->next_ != nullptr)
    {
      ptr = ptr->next_;
      return temp;
    }
    else
      return *this;
  }

测试代码(带后缀的atm):

List<int> list1 {324, 2, 3};
  List_const_iterator_<int> clst = list1.cbegin();
  clst = clst++;
  cout << "val: " << clst.ptr->data_ << endl;
  clst = clst++;
  cout << "val2: " << clst.ptr->data_ << endl;
 clst = clst++;
  cout << "val3: " << clst.ptr->data_ << endl;

后缀的输出:

val: 324
val2: 324
val3: 324

前缀的输出:

val: 2
val2: 3
val3: 3  <-- This is where we segfault if we don't use the controll.

最佳答案

试试 :

clst++;

代替:

clst = clst++;

后者将 clst 重置为其原始值(就好像增量没有发生一样)。

关于c++ - 迭代器和 const_iterator operator++ post and prefix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22983680/

相关文章:

c++ - 从 x64 注入(inject)器注入(inject)带有 x86 dll 的 x86 目标

c++ - 带有可变参数模板包的类模板的输出运算符

c++ - Boost.Fusion 功能 : Calling functions with default arguments

c++ - 当前面为 0 时,scanf 读取错误的整数

c++ - 如何在C++中调用Web服务方法?

c++ - 从 std::map 插入/删除元素是否会修改迭代序列?

c++ - 如何更改定界符的位置?

c++ - 在 C++ 中将惰性生成器实现为 forward_iterator

c++ - 重载输入/输出运算符

c++ - 用类和 vector 重载赋值运算符