c++ - 如何获得正确答案合并 2 个排序数组?! C++

标签 c++ arrays sorting merge

<分区>

我为 marge 写了一个小算法到排序数组。但我对此有疑问。

#include <iostream>
using namespace std;

int main() {

    // main function started form here:

    int firstArray[10] = {1,3,5,7,9,11,13,15,17,19};
    int secondtArray[10] = {2,4,6,8,10,12,14,16,18,20};

    int mergedArray[20];
    int firstCounter=0 , secondtCounter=0 , mergedCounter=0;

    while(firstCounter < 10 && secondtCounter < 10){
        if(firstArray[firstCounter] < secondtArray[secondtCounter]){
            mergedArray[mergedCounter] = firstArray[firstCounter];
            firstCounter++;
        } else {
            mergedArray[mergedCounter] = secondtArray[secondtCounter];
            secondtCounter++;
        }
        mergedCounter++;
    }

    while(firstCounter < 10) {
        mergedArray[mergedCounter] = firstArray[firstCounter];
        firstCounter++;
        mergedCounter++;
    }

    while(secondtCounter < 10) {
        mergedArray[mergedCounter];
        secondtCounter++;
        mergedCounter++;
    }

    for(int j=0; j<20; j++){
        //cout << mergedArray[j] << endl;
    }
    cout << mergedArray[19];

    return 0;
}

在数组 mergedArray[19] 的输出中,我得到这样的结果:2686916!!!

我不知道为什么我得到这个值。我该如何解决。以及为什么我得到这个值。

最佳答案

上次打字错误。您可以提高警告级别,让您的编译器显示您的拼写错误(warning: statement has no effect [-Wunused-value])。

while(secondtCounter < 10) {
    mergedArray[mergedCounter];
    secondtCounter++;
    mergedCounter++;
}

应该是

while(secondtCounter < 10) {
    mergedArray[mergedCounter] = secondtArray[secondtCounter];
    secondtCounter++;
    mergedCounter++;
}

关于c++ - 如何获得正确答案合并 2 个排序数组?! C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21814706/

相关文章:

c++ - 使用 curl 的 mobotix 相机

javascript - 将两个数组合并为所有可能组合的数组的算法

javascript - 如何对包含日期和值的数组进行排序?

c++ - lambda 可以用作非类型模板参数吗?

c++ - 在调试器中查看 C++ shared_ptr 内容

php - 我有一个数组,但现在如何插入 csv 值 php mysql

Java 多维数组初始值设定项

javascript:最快的查找方式是字符串位于一组字符串中

javascript - 在数字排序期间保持精度

c++ - C++ 中奇怪的 std::stringstream 行为