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.