how to iterate struct in C++?
Same way as you would iterate anything that doesn't have a pre-existing standard iterator: By writing a custom iterator.
Writing custom iterators isn't simple, and writing this custom iterator is particularly complex due to lack of introspective language features, , . An incomplete, simplified example:
struct Flags
{
bool isATrue;
bool isBTrue;
bool isCTrue;
struct iterator {
Flags* flags;
int index;
bool& operator*() {
switch(index) {
case 0: return flags->isATrue;
case 1: return flags->isBTrue;
case 2: return flags->isCTrue;
default: throw std::out_of_range("You wrote a bug!");
}
}
iterator& operator++() {
index++;
return *this;
}
iterator operator++(int) {
iterator next = *this;
index++;
return next;
}
friend auto operator<=>(const iterator&, const iterator&) = default;
};
iterator begin() {
return {this, 0};
}
iterator end() {
return {this, 3};
}
};
Note that although it is possible to iterate members of a class in C++, this is not necessarily efficient. It may be advisable to use an array instead of a class if you need efficient iteration.
std::mapor some other container is what you want, rather than a struct?std::bitset. This might be what you are looking forstd::bitsetdoes not providebeginandend–std::array<bool, N>might be an alternative, allowing range based for loop (losing advantage of compressed bools, gaining slightly faster access). In any case you might want to have an enum identifying the indices such that you can do e. g.allFlags[CFlag]to access what was formerlyisCTrue.