function composition in C++ / C++11

前端 未结 7 1486
北荒
北荒 2020-12-01 09:38

I am currently coding some cryptographic algorithms in C++11 that require a lot of function compositions. There are 2 types of composition I have to deal with :

7条回答
  •  無奈伤痛
    2020-12-01 10:22

    You haven't shown the body of F, but if you can modify it so that it mutates the input to form the output then change the signature to:

    void F(std::vector& x);
    

    Thereafter you can implement Fn as:

    void Fn(std::vector& x, size_t n)
    {
        for (size_t i = 0; i < n; i++)
            F(x);
    }
    

    The compiler will unroll the loop for you if it is more efficient, but even if it doesn't an increment/compare of a local variable will be orders of magnitude faster than calling F.

    You can then explcitly copy-construct new vectors when you actually want to make a copy:

    vector v1 = ...;
    vector v2 = v1; // explicitly take copy
    Fn(v2,10);
    

提交回复
热议问题