【问题标题】:Misunderstanding of range-based for loop?对基于范围的for循环的误解?
【发布时间】:2013-02-19 18:53:16
【问题描述】:

当我尝试编译以下代码时出现编译器错误:

for(binary_instructions_t &inst: BinaryInstructions){


}

BinaryInstructions 是这个枚举类:

typedef unsigned int binary_instructions_t;

enum class BinaryInstructions : binary_instructions_t
{
    END_OF_LAST_INSTR = 0x0,

    RESET,
    SETSTEP,
    START,
    STOP,

    ADD,
    REMOVE,
};

是否应该允许我使用枚举类中的项目“做一个”基于 for 循环的范围?还是我巧妙地误解了基于范围的 for 循环是用于搜索数组的内容而不是枚举类之类的东西?

我也试过:创建实例并在实例内搜索:

BinaryInstructions bsInstance;
for(binary_instructions_t &inst : bsInstance){


}

但没有雪茄...提前致谢,

【问题讨论】:

    标签: c++ for-loop enum-class


    【解决方案1】:

    基于范围的 for 循环需要一个集合,如数组或向量。枚举类不是一个集合。

    但是,它是 C++,所以有一个解决方法。见:Allow for Range-Based For with enum classes?

    【讨论】:

    • 太甜了!我喜欢那个实现。比我使用的转换为 int 的解决方案要干净得多。
    【解决方案2】:

    基于范围的 for 循环是一种在元素列表上轻松迭代的机制。 “元素列表”可以是普通数组,也可以是实现 beginend 方法并返回迭代器类型的类的实例。

    例子:

    int arr[] = { 1, 2, 3, 4 };
    for (int cur : arr)
       std::cout << cur << std::endl;
    

    【讨论】:

      猜你喜欢
      • 2016-10-31
      • 1970-01-01
      • 2014-12-06
      • 2014-01-12
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-26
      相关资源
      最近更新 更多