【发布时间】:2011-05-02 05:41:57
【问题描述】:
我编写了以下函数,通过根据需要添加行或列(其中 sizeX、sizeY、get、set 和 resize 是不言自明的 grid2D 成员函数)来制作奇维的二维数组对象。
void makeOdd(grid2D<double> *pSrc)
// ---------------------------------------------------------------------------------------------------------
// Make one or both dimensions of input array odd (via row/column copy).
{
// Variable declarations
grid2D<double> pTmp = *pSrc; // Scratch local source variable
int simax, sjmax; // Source dimensions
// Get source dimensions
sjmax = pSrc->sizeY();
simax = pSrc->sizeX();
// Check if source is already odd-dimensioned
if (sjmax%2 && simax%2) return;
// Extend row/column of source if necessary
if (sjmax%2 && !(simax%2)) // Odd rows, even columns
{
pSrc->resize(simax+1,sjmax); // Resize source with extra column
for(int i=0; i<simax+1; i++)
{
for(int j=0; j<sjmax; j++)
{
if(i==simax)
pSrc->set(i,j,pTmp.get(simax-1,j)); // Copy last column
else
pSrc->set(i,j,pTmp.get(i,j));
}
}
return;
}
else if (!(sjmax%2) && simax%2) // Even rows, odd columns
{
pSrc->resize(simax,sjmax+1); // Resize source with extra row
for(int i=0; i<simax; i++)
{
for(int j=0; j<sjmax+1; j++)
{
if(i==simax)
pSrc->set(i,j,pTmp.get(i,sjmax-1)); // Copy last row
else
pSrc->set(i,j,pTmp.get(i,j));
}
}
return;
}
else // Even rows, even columns
{
pSrc->resize(simax+1,sjmax+1); // Resize source with extra row and column
for(int i=0; i<simax+1; i++)
{
for(int j=0; j<sjmax+1; j++)
{
if(i==simax && j==sjmax)
{
pSrc->set(i,j,pTmp.get(simax-1,sjmax-1)); // Copy last column and row
}
else if(i==simax && j<sjmax)
{
pSrc->set(i,j,pTmp.get(simax-1,j)); // Copy last column
}
else if(i<simax && j==sjmax)
{
pSrc->set(i,j,pTmp.get(i,sjmax-1)); // Copy last row
}
else
{
pSrc->set(i,j,pTmp.get(i,j));
}
}
}
return;
}
}
我的问题:有没有更清洁/更有效的方法?
非常感谢...
【问题讨论】:
-
你到底想在这里做什么?
-
例如,如果我有一个尺寸为 10x10 的双精度数组 X,我想通过复制最后一行和最后一列来使 X 的尺寸为 11x11。
标签: c++ syntax multidimensional-array dimensions