Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Misunderstanding of range-based for loop?

A compiler error occurs when I try to compile the following code:

for(binary_instructions_t &inst: BinaryInstructions){


}

BinaryInstructions is this enum class:

typedef unsigned int binary_instructions_t;

enum class BinaryInstructions : binary_instructions_t
{
    END_OF_LAST_INSTR = 0x0,

    RESET,
    SETSTEP,
    START,
    STOP,

    ADD,
    REMOVE,
};

Should I be allowed to "do a" range based for loop using the items inside an enum class? Or have I subtly misunderstood in that range based for loops are for searching the contents of an array and not stuff like enum classes?

I have also tried: Creating an instance and searching within the instance:

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


}

But no cigar... Thanks in advance,

like image 928
FreelanceConsultant Avatar asked Feb 19 '13 18:02

FreelanceConsultant


People also ask

Are range-based for loops slower?

Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once. Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).

What is a ranged based for loop?

Range-based for loop in C++It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

What is a range-based for loop How does it differ from a normal for loop?

Basically, range-based loops are faster to be typed (with less characters), while ordinary for loops are more generic. Ordinary loops perform init/condition/effect, whereas foreach loops work directly with iterators. You can model one in the other, but that doesn't make them equivalents.

Does a range-based for loop use iterators?

Range-based for loops work with all standard container types. They're really just a shortcut for certain iterator operations. The type named std::vector<int>::iterator is just another class defined in the standard library.


1 Answers

The range-based for loop needs a collection, like an array or a vector. The enum class isn't a collection.

However, it's C++, so there's a workaround. See: Allow for Range-Based For with enum classes?

like image 165
Seth Avatar answered Oct 05 '22 09:10

Seth