• C++比较两个数组是否相等(详解版)

    不能使用 == 运算符与两个数组的名称来确定数组是否相等。以下代码似乎是在比较两个数组的内容,但实际上并不是。

    int arrayA[] = { 5, 10, 15, 20, 25 };
    int arrayB[] = { 5, 10, 15, 20, 25 };
    if (arrayA == arrayB) // 语句错误
        cout << "The arrays are the same. \n";
    else
        cout << "The arrays are not the same.\n";

    在对数组名称使用 == 运算符时,运算符会比较数组的开始内存地址,而不是数组的内容。这个代码中的两个数组显然会有不同的内存地址。因此,表达式 arrayA == arrayB 的结果为 false,代码将报告数组不相同。

    要比较两个数组的内容,则必须比较它们各自的元素。例如,请看以下代码:

    const int SIZE = 5;
    int arrayA[SIZE] = { 5, 10, 15, 20, 25 };
    int arrayB[SIZE] = { 5, 10, 15, 20, 25 };
    bool arraysEqual = true; // 标志变量
    int count = 0; //循环控制变量
    
    //确定元素是否包含相同的数据
    while (arraysEqual && count < SIZE)
    {
        if (arrayA[count] != arrayB[count])
            arraysEqual = false;
        count++;
    }
    //显示合适的消息
    if (arraysEqual)
        cout << "The arrays are equal.\n";
    else
        cout << "The arrays are not equal.\n";

    此代码确定 arrayA 和 arrayB 是否包含相同的值。初始化为 true 的 bool 变量 arraysEqual 将表示数组是否相等。另一个初始化为 0 的变量 count 被用作循环计数器。

    接下来开始一个 while 循环。只要 arraysEqual 为 true 并且计数器变量 count 小于 SIZE,循环就会执行。在每次迭代中,它会比较数组中不同的对应元素。如果它找到两个具有不同值的相应元素,那么 arraysEqual 变量将设置为 false,这将允许退出循环而不检查更多值。

    循环完成后,if 语句将测试 arraysEqual 变量。如果变量仍然为 true,则说明没有发现差异,数组是相等的,然后就会显示一条消息指示该结论;否则,数组不相等,又会显示另外一条不同的消息。

更多...

加载中...