I have developed an algorithm to change control flags into an specific order. Think of it as a counter or a clock where you could define minimum, maximum, step, and so on. But every time I want to use it, I need to copy-paste several lines of code and change some lines in the middle.
I was wandering if there is a way of implementing this new flow control statement. My question could be also stated as "how do I write a function where I require a simple or a compound C++ statement as an argument"?
Another way of approaching my question is to figure out how could I convert the following code:
int a;
vector<int> av;
for(int i = 0; i < 10; i++)
{
a = (i > a)? i : i*2;
av.push_back(a);
}
for(int i = 20; i >= 10; i--)
{
a = ((a+i)%2 == 1)? 0 : i/2;
av.push_back(a*3);
}
into something close to this:
// definition
void another_for_loop(const int &a, const int &b, const int &inc_, [????] )
{
inc = (inc_ == 0) ? 1 : inc_;
if(inc > 0)
{
for(int i = min(a,b); i <= max(a,b); i += inc)
[????];
}
else
{
for(int i = max(a,b); i >= min(a,b); i += inc)
[????];
}
}
// [...]
// inside main{}
int a;
vector<int> av;
another_for_loop(0, 9, 1, {a = (i > a)? i : i*2; av.push_back(a);});
another_for_loop(10, 20, -1, {a = ((a+i)%2 == 1)? 0 : i/2; av.push_back(a*3);});
Hope there is a clever way to do so... :-D
Even if there is no way, please, let me know.
You may use functor and lambda:
// definition
template <typename F>
void another_for_loop(const int &a, const int &b, const int &inc_, F f)
{
int inc = (inc_ == 0) ? 1 : inc_;
if(inc > 0)
{
for(int i = min(a,b); i <= max(a,b); i += inc)
f(i);
}
else
{
for(int i = max(a,b); i >= min(a,b); i += inc)
f(i);
}
}
And then
int a = 0;
vector<int> av;
another_for_loop(0, 9, 1, [&a, &av](int i){a = (i > a)? i : i*2; av.push_back(a);});
another_for_loop(10, 20, -1, [&a, &av](int i){a = ((a+i)%2 == 1)? 0 : i/2; av.push_back(a*3);});