C ++:我做错了什么?

时间:2022-09-06 21:36:51

I just wrote a piece of code to merge 2 sorted arrays. The merging works fine. However when i try to print the sorted array. I get just a bunch of 1's repeated

我刚写了一段代码来合并2个排序的数组。合并工作正常。但是当我尝试打印排序的数组时。我只重复了一堆1

My code:

#include <iostream>
using namespace std;
#define G_N_ELEMENTS(arr) ((sizeof(arr))/(sizeof(arr[0])))

class mergeArray{
    public:
    int *A,*B,*C;
    mergeArray(int *A,int *B)
    {
        this->A = A;
        this->B = B;
    }
    void  mergeArrays(int sizeA,int sizeB)
    {
        int newSize = sizeA+sizeB;
        C = new int[newSize+1];
        int i=0,j=0,k=0;
        while(k<newSize)
        {
            if(*(A+i)<*(B+j))
            {
                *(C+k)=*(A+i);
                if(i<sizeA)i++;
            }
            else
            {
                *(C+k)=*(B+j);
                if(j<sizeB)j++;
            }
            k++;
        }
        *(C+newSize) = -1;
    }
    void printMergeArray()
    {
        int i=0;
        while(*(C+i)!=-1)
        {
            cout<< *(C+i)<<endl;
        }
    }

};
int main(int argc, char **argv)
{
    int A[5]={1,3,5,7,9};
    int B[5]={2,4,6,8,10};
    mergeArray mm(A,B);
    int sizeA = G_N_ELEMENTS(A);
    int sizeB = G_N_ELEMENTS(B);
    mm.mergeArrays(sizeA,sizeB);
    mm.printMergeArray();
    return 0;
}

What am I doing wrong? I debugged the code using gdb. And the merge works fine and when I print using the GDB print command the merged array has correct values.

我究竟做错了什么?我使用gdb调试了代码。合并工作正常,当我使用GDB打印命令打印时,合并的数组具有正确的值。

1 个解决方案

#1


1  

I realize that you already have your answer from one of the comments - you are not incrementing the index in printMergeArray.

我意识到你已经从其中一条评论中得到了答案 - 你没有在printMergeArray中增加索引。

My motivation for this answer is to suggest some stylistic changes:

我对这个答案的动机是建议一些风格上的变化:

I think while loops of the form

我认为while循环的形式

while(k<newSize)
{
    k++;
}

are inferior to the form:

不如形式:

for( k = 0; k < newSize; ++k)
{
}

Also,

*(C+k)=*(A+i);
if(i<sizeA)i++;

can be replaced by stronger assertion.

可以用更强的断言取而代之。

assert(i < sizeA);
*(C+k)=*(A+i);
i++;

Similarly,

*(C+k)=*(B+j);
if(j<sizeB)j++;

can be replaced by:

可以替换为:

assert(j < sizeB);
*(C+k)=*(B+j);
j++;

#1


1  

I realize that you already have your answer from one of the comments - you are not incrementing the index in printMergeArray.

我意识到你已经从其中一条评论中得到了答案 - 你没有在printMergeArray中增加索引。

My motivation for this answer is to suggest some stylistic changes:

我对这个答案的动机是建议一些风格上的变化:

I think while loops of the form

我认为while循环的形式

while(k<newSize)
{
    k++;
}

are inferior to the form:

不如形式:

for( k = 0; k < newSize; ++k)
{
}

Also,

*(C+k)=*(A+i);
if(i<sizeA)i++;

can be replaced by stronger assertion.

可以用更强的断言取而代之。

assert(i < sizeA);
*(C+k)=*(A+i);
i++;

Similarly,

*(C+k)=*(B+j);
if(j<sizeB)j++;

can be replaced by:

可以替换为:

assert(j < sizeB);
*(C+k)=*(B+j);
j++;