数组连续零替换为单个零的C++代码故障排查与修复建议
修复C++连续零压缩代码的问题
需求
输入一个包含大量零元素的数组,将所有连续的零组替换为单个零。
原代码
#include <iostream> using namespace std; int main() { int size = 0, new_size=0, zero_streak = 0; cout << "Input length of an array: "; cin >> size; double *arr = new double[size]; double* arr2{ new double[size] }; cout << "\nInput elements of an array:\n"; for (int index = 0; index < size; index++) { cin >> arr[index]; } for (int index = 0; index < size; index++) { if (arr[index] == 0) { ++zero_streak; if (zero_streak == 1 || zero_streak == 0) { arr2[index]=arr[index]; ++new_size; } } else if (arr[index] != 0) { arr2[index] = arr[index]; ++new_size; zero_streak = 0; } } cout << "\nNew array looks like this:\n"; for (int index = 0; index < new_size; index++) cout << arr2[index] << " "; delete[] arr; delete[] arr2; return 0; }
存在的问题
运行代码时会出现两个问题:
- 首个零之后的连续零会输出未知值(未初始化的内存内容)
- 原数组的最后一个元素无法正确复制到新数组中
问题原因分析
- 新数组索引错误:原代码直接使用原数组的
index给新数组arr2赋值,但新数组元素数量少于原数组(连续零被压缩),导致arr2大量位置未初始化,输出时出现未知值;同时原数组与新数组元素位置不对应,最后一个元素可能无法被放到新数组的有效位置。 - 连续零判断逻辑冗余:在零元素分支中,
zero_streak会先自增,zero_streak == 0的情况永远不会出现,该判断完全多余。
修复后的代码
#include <iostream> using namespace std; int main() { int size = 0, new_size = 0, zero_streak = 0; cout << "输入数组长度: "; cin >> size; double *arr = new double[size]; double* arr2 = new double[size]; cout << "\n输入数组元素:\n"; for (int index = 0; index < size; index++) { cin >> arr[index]; } // 用独立索引追踪新数组的当前写入位置 int new_index = 0; for (int index = 0; index < size; index++) { if (arr[index] == 0) { zero_streak++; // 仅在遇到连续零的第一个元素时写入新数组 if (zero_streak == 1) { arr2[new_index] = arr[index]; new_index++; new_size++; } } else { // 非零元素直接写入,重置连续零计数 arr2[new_index] = arr[index]; new_index++; new_size++; zero_streak = 0; } } cout << "\n处理后的数组:\n"; for (int index = 0; index < new_size; index++) cout << arr2[index] << " "; delete[] arr; delete[] arr2; return 0; }
修复说明
- 新增
new_index变量专门追踪新数组的写入位置,彻底解决索引错位问题 - 简化连续零判断逻辑,仅在首次遇到零时写入新数组,避免重复添加
- 统一指针初始化风格,提升代码可读性
- 将控制台提示改为中文(如需英文可改回原提示)
内容的提问来源于stack exchange,提问作者Nikita Struk
相关产品推荐
相关产品推荐

