Search code examples
c++functionevalpolynomials

Generate functions with a function in C++


I am working with C++ and need to generate a matrix whose elements are the monomials of a power series, evaluated at various coordinates. For example, suppose each row of my matrix is generated by evaluating the monomials 1, x, y, x*x, x*y, y*y, at coordinates (x,y) = (-1,-1), (0,0), (1,1), then it is written as:

1 -1 -1 1 -1 1
1 0 0 0 0 0
1 1 1 1 1 1

In practice, both the list of monomials and coordinates are variable. For example, I may want to extend the monomial list into a higher dimension and order, and the coordinates can be arbitrarily large.

Currently, I can generate the monomial list using strings, but I need to somehow translate the strings into variables which can take up the numerical values. Is this possible in C++?


Solution

  • You can return std::array/std::vector from functions/lambdas:

    std::vector<int> createRow(int x, int y)
    {
        return {1, x, y, x * x, x * y, y * y};
    }
    
    template <typename RowGenerator>
    std::vector<std::vector<int>>
    createMatrix(RowGenerator gen, const std::vector<std::pair<int, int>>& input)
    {
        std::vector<std::vector<int>> res(input.size());
    
        std::transform(input.begin(), input.end(), res.begin(), gen);
        return res;
    }