我在嘗試按列更改行時遇到了一些麻煩。交換C++中的列的行
我想要的是改變靜態二維數組(3x3)的行和列。我不想只打印帶有反向索引的數組。我試圖在int aux中存儲數組中實際位置的值,但沒有效果。
輸入:
1 2 3
4 5 6
7 8 9
輸出:
1 4 7
2 5 8
3 6 9
利用該代碼,結果是相同的2D陣列。我看不出問題,你能幫我嗎?
#include <iostream>
using namespace std;
int main()
{
int vec[3][3];
int x, y, aux;
//Input
for(x=0; x<3;x++)
{
for(y=0; y<3;y++)
{
cout << "POSITION ["<<x+1<<"]["<<y+1<<"]: ";
cin >> vec[x][y];
}
}
cout<<"\nPress ENTER...";
cin.ignore();
cin.get();
system("CLS");
//Array before the change
cout<<"ARRAY A"<<endl;
for(x=0; x<3;x++)
{
for(y=0; y<3;y++)
{
cout<<vec[x][y]<<"\t";
}
cout << "\n";
}
//Change
for(x=0; x<3;x++)
{
for(y=0; y<3;y++)
{
if(x!=y)
{
aux=vec[x][y];
vec[x][y]=vec[y][x];
vec[y][x]=aux;
}
}
}
//Array after the change
cout<<"\nARRAY A"<<endl;
for(x=0; x<3;x++)
{
for(y=0; y<3;y++)
{
cout<<vec[x][y]<<"\t";
}
cout << "\n";
}
cout << "\n";
system("PAUSE");
return 0;
}
這種操作稱爲「矩陣轉置」;如果你搜索這個短語,你會發現一些相關的討論。 – IvyMike
聽起來像是[BLAS](http://www.netlib.org/blas/)或[CBLAS](https://www.gnu.org/software/gsl/manual/html_node/GSL-CBLAS)的操作-Library.html) – Mgetz