c++ - 如何为特殊情况定义迭代器,以便使用 auto 关键字在 for 循环中使用它

标签 c++

我想定义后续代码以便能够像这样使用它 "for (auto x:c0){ printf("%i ",x); }"

但是我有一点不明白,我已经搜索了一段时间。

我得到的错误是: 错误:一元‘*’的无效类型参数(有‘CC::iterator {aka int}’)

#include <stdio.h>

class CC{
  int a[0x20];
  public: typedef int iterator;
  public: iterator begin(){return (iterator)0;}
  public: iterator end(){return (iterator)0x20;}
  public: int& operator*(iterator i){return this->a[(int)i];}
} ;

int main(int argc, char **argv)
{ class CC c0;
  for (auto x:c0){
    printf("%i ",x);
  }
  printf("\n");
  return 0;
}

最佳答案

您似乎正在尝试使用 int当您使用成员 operator*() 进行迭代时作为尊重操作。那行不通:

  1. operator*()您定义的是二元运算符(乘法)而不是一元取消引用运算。
  2. 您不能为内置类型重载运算符,迭代器类型需要有解引用运算符。

为了能够使用基于范围的 for你需要创建一个前向迭代器类型,它需要几个操作:

  1. 生命周期管理,即复制构造函数、复制赋值和销毁(通常生成的就足够了)。
  2. 定位,即operator++()operator++(int) .
  3. 值访问,即 operator*()并且可能是 operator->() .
  4. 有效性检查,即operator==()operator!=() .

像这样应该就足够了:

class custom_iterator {
    int* array;
    int  index;
public:
    typedef int         value_type;
    typedef std::size_t size_type;
    custom_iterator(int* array, int index): array(array), index(index) {}
    int& operator*()             { return this->array[this->index]; }
    int const& operator*() const { return this->array[this->index]; }
    custom_iterator& operator++() {
        ++this->index;
        return *this;
    }
    custom_iterator  operator++(int) {
        custom_iterator rc(*this);
        this->operator++();
        return rc;
    }
    bool operator== (custom_iterator const& other) const {
        return this->index = other.index;
    }
    bool operator!= (custom_iteartor const& other) const {
        return !(*this == other);
    }
};

begin()end()然后方法将返回此迭代器的适当构造版本。您可能希望将迭代器与合适的 std::iterator_traits<...> 连接起来。但我认为使用基于范围的 for 不需要这些.

关于c++ - 如何为特殊情况定义迭代器,以便使用 auto 关键字在 for 循环中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20730817/

相关文章:

java - 在 CNI/C++ 代码中实例化模板类

c++ - 为范围内的所有数字返回相同值的哈希?

c++ - 在 C++ 中读取所有文件被 .文件夹

c++ - 接收问题时套接字关闭

c++ - 将项目推回 vector 中包含的 vector 时出现未处理的异常

c++ - c_str 是否总是返回相同的地址?

c++ - 简单的 CUDA 应用程序,cudaMalloc 以错误 : unspecified driver error 结束

c++ - 如何在不显示 Win32 GUI 程序的控制台窗口的情况下执行子控制台程序?

c++ - 如何排序 vector <pair<string , pair<int , int>>>?

c++ - 无法将参数 1 从 'cli::interior_ptr<Type>' 转换为 'CvCapture **'