我有一个值矩阵(存储为值数组)和一个具有矩阵维度(dims[d0, d1, d2])的 vector 。 我需要构建一个这样的字符串: “matA(j, k, l) = x;” 其中 j、k、l 是矩阵的索引,x 是元素的值。我需要为矩阵的每个值和 2 到 n 维的矩阵编写此代码。
我在分离基本案例并以有用的方式复制它时遇到了问题。我在 switch case 中做了一个版本,每个维度都有一个 case,for 循环的数量等于维度的数量:
for (unsigned int k=1; k<=(dims[2]); k++)
{
for (unsigned int j=1; j<=(dims[1]); j++)
{
for (unsigned int i=1; i<=(dims[0]); i++)
{
strs << matName << "(" << i << "," << j << ","<< k << ")="<< tmp[t]<< "; ";
....
但这不是我想要的。对于具有可变维数的更一般情况有什么想法吗?
最佳答案
您需要一个单独的 worker 函数来递归生成一系列索引和对其进行操作的 main 函数。
例如类似的东西
void worker(stringstream& strs, int[] dims, int dims_size, int step) {
if (step < dims_size) {
... // Add dims[step] to stringstream. Another if may be necessary for
... // whether include `,` or not
worker(strs, dims, dims_size, step + 1);
} else {
... // Add cell value to stringstream.
}
}
string create_matrix_string(int[] dims, int dims_size, int* matrix) {
... // Create stringstream, etc.
strs << ... // Add matrix name etc.
worker(strs, dims, dims_size, 0);
strs << ... // Add ending `;` etc.
}
这里的主要问题是值,因为维度在编译期间是未知的。您可以通过在一维表中编码矩阵来避免这种情况(好吧,这就是 C++ 对静态多维表所做的事情)并使用手动计算的索引调用它,例如。 i + i * j
(二维表)。同样,您可以通过递归传递一个累加值并在最后一步使用它(我在上面的示例中省略了)来做到这一点。您可能必须传递其中两个(多项式分量的运行总和,以及 i * j * k * ... * x
到目前为止已完成步骤的索引的乘积。
所以,上面的代码远未完成(和清洁),但我希望思路清晰。
关于c++ - 在 C++ 中使用递归构建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20563939/