I can clearly do something like this:
for(int i = 0; i < 10000; i++)
testIteration();
But is there any std functions which does similar thing in one line? Something like that:
std::repeat(10000, testIteration);
In the proposed standard for C++20 there is an example for iota_view
:
for (int i : iota_view{1, 10})
cout << i << ' '; // prints: 1 2 3 4 5 6 7 8 9
But for now, range-v3 library can be used:
for (int _ : view::iota{0, 10})
testIteration(); // calls testIteration 10 times.
But is there any std functions which does similar thing in one line?
No, there is no algorithm in the standard library to do this (at least nothing that would not require to write useless boilerplate). As others already mentioned a loop is the most readable and least obfuscated way to do "something" n-times.
That being said, if you take it as an exercise to get a more terse syntax, you could write this:
#include <iostream>
struct my_counter {
int stop;
struct iterator {
int count;
iterator& operator++() { ++count; return *this; }
int operator*() { return count;}
bool operator!=(const iterator& other) { return count != other.count; }
};
iterator begin() { return {0}; }
iterator end() { return {stop};}
};
void print() { std::cout << "x"; }
int main() {
for (auto x : my_counter{5}) print();
}
However, I would strongly advise against using something like that. Everybody knows how a loop works and what it does. Being used to for loops you can read a for loop in a blink, while anything else is uncommon, surprising and obfuscating, unless there is a standard algorithm of course (though I doubt that an algorithm for this particular case would be of great use). Why reinvent the wheel when you can use a loop?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With