2015-12-06 16 views
-3

我想使用C++代碼將以下兩個二維數組AB合併到一個二維數組C中。之後,我嘗試先填充數組C,然後將數組B填入數組,但它不起作用。如何在C++中合併二維數組?

int A[3][2]={{1,2}, 
      {4,5}, 
      {7,8}}; 

int B[3][1]={{0}, 
      {4,}, 
      {7,}}; 

int C[3][3] = 
     { { 0, 1 ,2}, 
     { 4, 4, 5}, 
      {7 ,7 ,8}} 

我使用的代碼是:

// merge part 
for(int i = 0; i <3; i++) 
    { 
     for(int j = 0; j < 3; j++) 
     { 
      if(i<1) 
      { 
       C[i][j] = B[i][j]; 
      } 
      else 
      { 
       C[i][j] =A[i-1][j] ; 
      } 
     } 
    } 
    cout<<"\n\n\C: "<<endl; 

    for(int i = 0; i < 3; i++) 
    { 
     for(int j = 0; j < 3; j++) 
     { 
      cout<<C[i][j]; 
     } 
    } 

回答

0

您可以使用標準算法std::merge在頭部聲明<algorithm>

例如

#include <iostream> 
#include <algorithm> 
#include <iterator> 

int main() 
{ 
    int A[3][2] = 
    { 
     { 1, 2 }, 
     { 4, 5 }, 
     { 7, 8 } 
    }; 

    int B[3][1] = 
    { 
     { 0 }, 
     { 4 }, 
     { 7 } 
    }; 

    int C[3][3]; 

    for (size_t i = 0; i < 3; i++) 
    { 
     std::merge(std::begin(A[i]), std::end(A[i]), 
        std::begin(B[i]), std::end(B[i]), 
        std::begin(C[i])); 
    } 

    for (const auto &row : C) 
    { 
     for (int x : row) std::cout << x << ' '; 
     std::cout << std::endl; 
    }   
    std::cout << std::endl; 
} 

程序輸出是

0 1 2 
4 4 5 
7 7 8 
+0

我得到以下編譯器錯誤,當我運行你給先生27 行的代碼:錯誤:'開始'不是'std –

+0

@AjayThakur的成員您是否包含標題? –

+0

@AjayThakur在任何情況下,你可以用A [i]和A [i] + 2替換std :: begin(A [i]]和std :: end(A [i]),std :: begin (B [i])和std :: end(B [i])爲B [i]和B [i] +1 –

0

問題在於你使用索引的方式。第一個(i)對應於行,第二個(j)對應於列。因此,代碼應該是:

for (int i = 0; i < 3; i++) { 
    for (int j = 0; j < 3; j++) { 
     if (j < 1) { 
      C[i][j] = B[i][j]; 
     } 
     else { 
      C[i][j] = A[i][j - 1]; 
     } 
    } 
} 
0

合併兩個二維數組中的一個代碼如下

#include<iostream> 
using namespace std; 
int main() 
{ 
    int i,j, a[5][5]={1,2,3,4,5,6,7,8 ,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}; 
    int b[5][5]={26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50}; 

int c[10][5]; 

for(i=0;i<10;i++) 
{for(j=0;j<5;j++) 
{c[i][j]=0; 
}} 
for(i=0;i<10;i++) 
{for(j=0;j<5;j++) 
{ 
if(i<=4) 
    c[i][j]=a[i][j]; 
if(i>=5) 
c[i][j]=b[i-4][j-5]; 

} 
} 

for(i=0;i<10;i++) 
{for(j=0;j<5;j++) 
{cout<<c[i][j]<<"\t"; 
}cout<<endl; 
} 
    system("pause"); 
return 0; 
}