用 C++ 中的函数生成函数

问题描述

我正在使用 C++,需要生成一个矩阵,其元素是幂级数的单项式,在不同的坐标处计算。例如,假设我的矩阵的每一行是通过评估单项式 1,x,y,x*x,x*y,y*y,在坐标 (x,y) = (-1,-1),( 0,0),(1,1),则写成:

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

实际上,单项式列表和坐标都是可变的。例如,我可能想将单项式列表扩展到更高的维度和阶数,坐标可以任意大。

目前,我可以使用字符串生成单项式列表,但我需要以某种方式将字符串转换为可以接受数值的变量。这在 C++ 中可能吗?

解决方法

您可以从函数/lambda 返回 std::array/std::vector

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;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...