Iteration over an enum

suggest change

There is no built-in way to iterate over an enumeration.

There are several ways.

enum E {
    Begin,
    E1 = Begin,
    E2,
    // ..
    En,
    End
};

for (E e = E::Begin; e != E::End; e = static_cast<E>(e + 1)) {
    // Do job with e
}

An enum class does not promote to an integer, so operator++ has to be implemented:

E& operator ++ (E& e)
{
    if (e == E::End) {
        throw std::out_of_range("for E& operator ++ (E&)");
    }
    e = E(static_cast<std::underlying_type<E>::type>(e) + 1);
    return e;
}
enum E {
    E1 = 4,
    E2 = 8,
    // ..
    En
};

std::vector<E> build_all_E()
{
    const E all[] = {E1, E2, /*..*/ En};

    return std::vector<E>(all, all + sizeof(all) / sizeof(E));
}

std::vector<E> all_E = build_all_E();

for (std::vector<E>::const_iterator it = all_E.begin(); it != all_E.end(); ++it) {
    E e = *it;
    // Do job with e;
}
enum E {
    E1 = 4,
    E2 = 8,
    // ..
    En
};

static constexpr std::initializer_list<E> all_E = {E1, E2, /*..*/ En};

for (auto e : all_E) {
    // Do job with e
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents