C++中的turbo数组问题

turbo Array issue in C++

本文关键字:问题 数组 turbo 中的 C++      更新时间:2023-10-16

我正在使用Turbo c++
我需要将所有包含0的元素向左移动类似于if数组包含以下值20 10 15 7 4 20 2
输出必须是这样-0 0 10 15 4 2

完整的问题是第一部分是将用户输入的数字替换为0,所以我输入20,它们被0替换
原始值->10|20|15|4|20|2|20
我写了一个代码来搜索和替换输出为10|0|15|4|0|2|0的值。现在我需要在左边收集这些0,就像这样0|0|0|10|15|4|2

代码也包括我写的

#include<iostream.h>
#include<conio.h>
void main()
{
    int A[100],no,val,found;
    clrscr();
    cout<<"Enter number of elements you want to insert ";
    cin>>no;
    for(int i=0;i<no;i++)
    {
        cout<<"Enter element "<<i+1<<":";
        cin>>A[i];
    }
    cout<<"Enter the number you want to search ";
    cin>>val;
    for(int j=0; j<no; j++)
    {
        if(A[j]==val)
            A[j]=0;
    }
    for(int k=0; k<no; k++)
    {
        cout<<A[k]<<"   ";
    }
    getch();
}

需要一些帮助。

以下是我的建议:

  1. 不需要#include <conio.h>,它是特定于平台的
  2. clrscr()函数调用会惹恼试图帮助您的人,因为先前的文本被擦除
  3. no变量需要根据数组
  4. 尝试使用std::cin.ignore(10000, 'n');而不是getch()

要使用0移动插槽,需要将值从旧位置复制到新位置,其中第一个新位置是零位置。

给定:

0 -->|10|  
1    |15|  
2    | 0|  
3    | 3|  
4    | 4|  

第一次迭代,将插槽2中的0与插槽2中的15交换:

0 -->|10|  
1    |15| --> | 0|
2    | 0| --> |15|  
3    | 3|
4    | 4|

第二次迭代,将插槽1中的0与插槽0中的10交换:

0 -->|10| --> | 0|  
1    | 0| --> |10|
2    |15| 
3    | 3|
4    | 4|

继续迭代,直到上一个槽的值为零值,或者上一个插槽位于数组的开头之前。

提示:您将需要两个索引,现在和以前

编辑1:示例代码

int swap_index = 0;  
int search_index = 0;  
#define MAX_NUMBERS 6
unsigned int numbers[6] = {10, 15, 0, 3, 4};
for (search_index = 0; search_index < MAX_NUMBERS; ++search_index)
{
  if (numbers[search_index] == 0)
  {
    swap_index = search_index - 1;
    while (swap_index > 0)
    {
      numbers[swap_index + 1] = numbers[swap_index];
      numbers[swap_index] = 0;
      --swap_index;
    }
  }
}

这个代码是一个基础。有些问题,如限额检查,是读者的责任来解决。