Home > database >  C equivalent to std::all_of but working with a range loop?
C equivalent to std::all_of but working with a range loop?

Time:11-11

I am trying to re-write a piece of code that currently looks like this:

if (nchildren > 8 && 
  parent->isChildValid(0) && 
  parent->isChildValid(1) && 
  parent->isChildValid(2) && 
  parent->isChildValid(3) && 
  ... 
  parent->isChildValid(7)
) {

}

It tests the parent->isChildValid(i) 8 times where i, is an index within the range [0:7] in this particular case. I was looking (as an exercise) for a way of making this more efficient (imagine the range changes later) using something that would be similar to std::all_of but I understand these functions only work with constructs that support iterators. So something like this:

std::all_of(0, 7, [&](int i){ return parent->isChildValid(i); });

Would of course not work. But I would like to know if there a similar/alternative options (I am sure there is)) without (of course) declaring i is a vector and setting its content with {0, 1, 2, 3, 4, 5, 6, 7}. I am trying to avoid this as well, and look instead for something similar to all_of but where I could set the min and max indices (range loop kind of) over which I'd like the function to be tested for.

edit: I can't use boost.

CodePudding user response:

In C 20, you can use views::iota and ranges::all_of to do this

  if (nchildren > 8 && 
      std::ranges::all_of(std::views::iota(0, 8), 
                          [parent](auto i) { return parent->isChildValid(i); })
  ) {

  }
  • Related