0

嗨,我只是在寻求帮助,我写了一段快速的代码来接收一个字符数组,然后它将通过一个函数运行,该函数将删除任何重复的字符我有一个​​小错误,因为它没有删除最后一个重复的字母是我也会在代码之后放入输出的代码..

#include <iostream>

#include <fstream>

#include <ostream>

using namespace std;

const int max_num_chars=10;

void deleteRepeats(char c[], int& size);


int main()
{
    char c[]={'a','b','b','b'};
    int c_size=4;

    cout<<"This Program reads characters into a partially filled array and then delete's repeats! \n";
    cout<<"Here is the original array \n";
    for (int i=0;i<c_size;i++)
    {
        cout<<c[i]<<"\n";
    }
    deleteRepeats(c, c_size);
    cout<<"Here is the array after the deleteRepeats function! \n";
    for (int i=0;i<c_size;i++)
    {
        cout<<c[i]<<"\n";
    }
    system("pause");
    return 0;
}
void deleteRepeats(char c[],int& size)
{
    int num = size;
    int start = 0;

    while(start != num)
    {
        char test = c[start];
        for(int i = start+1; i <= num;i++)
        {
            if(test==c[i])
            {
                for(int j = i;j<num;j++)
                    {
                    c[j] = c[j+1];
                    }
                num-=1;
            }
        }
    start +=1;
    }
    size = num;
}

这是输出......这个程序将字符读入一个部分填充的数组,然后删除重复!这是原始数组 a b b b 这是 deleteRepeats 函数后的数组!a b b 按任意键继续。. .

抱歉,我只是通过添加修复它的这段代码自己解决了这个问题

for(int j = i;j<num;j++)
                    {
                    c[j] = c[j+1];
                    }
                num-=1;
                start-=1; 
4

2 回答 2

1

尽管对此有更好的算法。在您的情况下:

在函数 "deleteRepeats" 内,在循环内 "for(int i = start+1; i <= num;i++)"

当您删除下一个相同的元素时,您正在增加“i”而不考虑现在在同一个“i”处删除后也可能存在重复的元素。

解决方案:删除元素后,也减少 i 的值。所以现在你的循环看起来像这样

for(int i = start+1; i <= num;i++)
    {
        if(test==c[i])
        {
            for(int j = i;j<num;j++)
                {
                c[j] = c[j+1];
                }
            num-=1;
          // correction
            i--;
          // correction
        }
    }

如果理解有问题,请回复...

于 2013-10-06T00:45:26.447 回答
0

当您只需要一个时,为什么还要有两个嵌套循环?

void deleteRepeats(char c[], int& size) {
    // Trivial case of empty array: do nothing.
    if(size <= 0) // Why is `size` a signed `int` and not `size_t`?
        return;

    // First character is automatically not a repetition.
    // So for each character from the second onward,
    // move it if it is different from the previous character,
    // otherwise skip over it.
    char* read = c + 1;
    char* write = read;
    char* end = c + size;
    char prev = *c;
    while(read != end) {
        if(*read != prev) {
            prev = *read;
            *write++ = prev;
        }
        ++read;
    }

    // Finish up.
    size = write - c;
}
于 2013-10-06T01:17:20.863 回答