2017-02-28 52 views
1

我試圖在2D數組的每一行中找到最大數字,並將其放在直徑上。我這樣做了,但我現在想要替換這個數字,而不是僅僅在diametrum上宣佈它們。我如何改變我的情況下的數字位置?這裏是代碼:如何在C++中更改2d數組中的數字的位置?

#include<iostream> 

using namespace std; 

int mac(int b[],int n) 
{ 
int i,max,c=0; 
max=b[0]; 
for(i=0;i<n;i++) 
{ 
    if(max<b[i]) {max=b[i];c=i;} 
} 
return c; 
} 

int main() 
{ 
int i,j,n; 
int c; 
int a[10][10],b[10]; 

cin>>n; 

for(i=0;i<n;i++)  
{ 
    for(j=0;j<n;j++) 
    { 
     cin>>a[i][j]; 
     cin.ignore(); 
    } 
} 

for(i=0;i<n;i++)  
{ 
    for(j=0;j<n;j++) 
     b[j]=a[i][j]; 
    c=mac(b,n); 
    /*Place where i should change something*/ 
    a[i][i]=a[i][c];  

} 

for(i=0;i<n;i++)  
{ 
    for(j=0;j<n;j++) 
    { 
     cout<<a[i][j]; 
    } 
    cout<<endl; 
} 
return 0; 
} 
+0

你想將矩陣中每一行的最大值保存到另一個數組中?請更具體地說明你想要什麼以及你有什麼錯誤。 –

+0

我現在編輯了我的帖子。 –

回答

0

你需要做swap。所以你必須定義一個臨時變量來保存[i] [i]的實際值。然後用最大值覆蓋位置[i] [i],最後您需要將溫度值置回到您找到最大值的位置。

/*Place where i should change something*/ 
int temp = a[i][i]; 
a[i][i] = a[i][c]; 
a[i][c] = temp; 
+0

Oooo,所以它就像當排序數組 –

+0

'swap'也用於排序。如何交換兩個變量是基本技術。 – elanius

+0

如果你正在使用C++ 11,你也可以調用'std :: swap'。 http://en.cppreference.com/w/cpp/algorithm/swap –

0

假定當n = 3,並且輸入爲1 2 3 4 5 6 7 8 9輸出應爲321 465 789

代碼應該是

#include <iostream> 
#include <vector> 

using namespace std; 

int main() { 
    vector< vector<int> > a; 
    size_t n; 
    cout<<"Enter number of value for N: "; 
    cin>>n; 

    a.reserve(n); 

    for (size_t i = 0; i<n;i++) { 
     a[i].reserve(n); 
     for (size_t j =0 ; j<n;j++) { 
      cin>>a[i][j]; 
     } 
    } 

    for (size_t i = 0; i<n;i++) { 
     size_t index = 0; 
     int max = INT_MIN; 
     for (size_t j =0 ; j<n;j++) { 
      if (a[i][j] >= max) { 
       max = a[i][j]; 
       index = j; 
      } 
     } 
     a[i][index] = a[i][i]; 
     a[i][i] = max; 
    } 

    cout<<"\nOutput\n"; 
    for (size_t i = 0; i<n;i++) { 
     for (size_t j =0 ; j<n;j++) { 
      cout<<a[i][j]<<" "; 
     } 
     cout<<endl; 
    } 
} 
+0

對不起,我無法複製它。我得到這個錯誤警告:比較帶符號和無符號整數表達式 –

+0

立即嘗試並共享您正在使用的編譯器和標誌 – user1918858

+0

g ++ -Wall -std = C++ 0x -o –