How can I make a variable always equal to the result of some calculations?

前端 未结 12 1757
傲寒
傲寒 2021-02-02 05:34

In math, if z = x + y / 2, then z will always change whenever we replace the value of x and y. Can we do that in programming

12条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 06:01

    You can get close to this with by using a lambda in C++. Generally, when you set a variable like

    int x;
    int y;
    int z{x + y};
    

    z will only be the result of x + y at that time. You'd have to do z = x + y; every time you change x or y to keep it update.

    If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like

    int x;
    int y;
    auto z = [&](){ return x + y; };
    cin >> x;
    cin >> y;
    cout << z();
    

    and now z() will have the correct value instead of the uninitialized garbage that the original code had.

    If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like

    auto z = [&](){ static auto cache_x = x; 
                    static auto cache_y = y; 
                    static auto cache_result = x + y;
                    if (x != cache_x || y != cache_y)
                    {
                        cache_x = x; 
                        cache_y = y; 
                        cache_result = x + y;
                    }
                    return cache_result;
    };
    

提交回复
热议问题