is there any way to apply if statement to all variables in c++

Viewed 133

if statements are usually implemented as if(variable > value) what if I have a number of variables and they all have an operation for example a decrement operation and I want that if the value of any of these variables reaches to 0 the program should replace it to 100. Is there a simple way to do that?

4 Answers

You can't do that by ordinary if but if you have a container containing your values, you can use std::transform and the condition you want, to do the following

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> vec = {1,4 ,-7, 0 ,-9, 9};//The container of the values
    //the following line does every thing
    std::transform(vec.begin(), vec.end(), vec.begin(), [](const int& i){return (i < 0)? 100:i; });
    //To display
    for(auto& el : vec)
        std::cout<< el << " ";

}

And this is another answer inspired by @user2962393 's answer

#include <iostream>

void cond(int & h){
    if( h < 0 )
        h=100;
}
template<typename T, typename... Ts>
void set_100_if_cond(T& x, Ts&... xs) {
    (cond(x), ... , cond( xs ));
}

int main() {
    int var1 {50};
    int var2 {0};
    int var3 {-9};
    set_100_if_cond(var1, var2, var3);
    std::cout << var1 << " " << var2 << " " << var3;
}

Since C++11 you can write

#include <algorithm>
#include <initializer_list>
if (std::max({a, b, c, d, ..., z}) > value){
}

assuming of course all the variables a to z have the same type; you can cast them if not. The ... is used here typographically; insert your actual variable names.

If all items are in a container, you can use std::any_of. Otherwise, you can wrap up pointers to them into a container and use the same algorithm. If you don't want to do that, you might just have to type it all out or get creative.

if any of these values reaches to 0 the program should replace it to 100.

One way to solve this kind of problem is by using variadic templates and recursion (C++11):

#include <iostream>

template<typename T>
void set_100_if_0(T& x) {
   if (x == 0) x = 100;
}

template<typename T, typename... TT>
void set_100_if_0(T& x, TT&... xx) {
    set_100_if_0(x);
    set_100_if_0(xx...);
}

int main() {
    int foo = 42;
    int bar = 0;
    int baz = 99;
    set_100_if_0(foo, bar, baz);
    std::cout << bar << std::endl;
}

The program will print 100.

Is there a simple way to do that?

Nope. Nothing in C++ is simple.

Related