In C++, I need a custom iterator that goes over an array, not all elements of which are marked as valid. Thus, the next() function must be a bit smarter than the one just doing ++iterator; I need it to check validity of the next element, skip it if not valid, and so forth till a valid element is found or encoutering the array end. Just wonder if there’s a more elegant way to do so, rather than checking all elements in a loop one by one. For example:
struct MyDataType {
// ...
bool _flagValid;
// ...
bool is_valid() { return _flagValid; }
};
MyDataType DataArray[DATA_ARRAY_SIZE];
// ...
uint32_t count_valid_ones () {
auto cout = 0U;
for (auto &d: DataArray) {
if (d.is_valid) count++;
}
return count;
}
But this way woud be preferable:
uint32_t count_valid_ones () {
auto cout = 0U;
auto __range = ValidOnesOnly(DataArray)
for (auto &d: __range) count++;
return count;
}
Dima Krutyx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.