我正在研究其中嵌套了“ for循环”的代码,通常用于矩阵计算。
下面是示例。
for( j = 0; j < col; j++ )
{
for( i = 0; i < rows; i++ )
{
float temp_var = *(mat1 + ( i * Col) + j );
for( k = 0; k < rows; k++ )
{
if( k != i )
{
if( *(mat1 + ( k * col) + j ) == temp_var )
{
count++;
}
}
}
*(mat1 + ( i * col) + j ) = count;
}
}
for( j = 0; j < rows; j++ )
{
count = 0;
for( i = 0; i < col; i++ )
{
float temp_var = *(mat1+ ( j * col) + i );
for( k = 0; k< col; k++)
{
if( k != i)
{
if( *(mat1 + ( j * col) + k ) == temp_var )
{
count = count + 2;
}
}
}
*(mat1 + ( j * col) + i ) = count;
}
}
一种将它们拆分为不同功能的方法。但是我想是否可以以更有效的方式进行优化并提高可读性。
一些使代码更具可读性和简洁性的小方法:
As(mat1 +(j * col)+ i)被多次重用,您可以将其存储在像]这样的变量中
auto myVar = (mat1+ ( j * col) + i );
这将使您的代码更具可读性。
奖金:每当您不需要for循环中的索引时,for(auto x:arr)可能是一个明智的选择。