使用函数从 C++ 中的数组中删除重复项

2022-01-12 00:00:00 function arrays segmentation-fault c++

我正在编写一个程序,该程序将用户输入整数到一个数组中,调用一个从该数组中删除重复项的函数,然后打印出修改后的数组.当我运行它时,它允许我将值输入到数组中,但是当我完成输入值时会给我一个分段错误"错误消息.我做错了什么?

I'm writing a program that has a user input integers into an array, calls a function that removes duplicates from that array, and then prints out the modified array. When I run it, it lets me input values into the array, but then gives me a "Segmentation fault" error message when I'm done inputing values. What am I doing wrong?

这是我的代码:

#include <iostream>

using namespace std;

void rmDup(int array[], int& size)
{
        for (int i = 0; i < size; i++)
        {
            for (int j = i + 1; j < size; j++)
            {
                if (array[i] == array[j])
                {
                    array[i - 1 ] = array[i];
                    size--;
                }
            }
        }
}
int main()
{
    const int CAPACITY = 100;
    int values[CAPACITY], currentSize = 0, input;

    cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";

    while (cin >> input)
    {
       if (currentSize < CAPACITY)   
       {
           values[currentSize] = input;
           currentSize++;
       }
    }

    rmDup(values, currentSize);

    for (int k = 0; k < currentSize; k++)
    {
            cout << values[k];
    }

    return 0;
}

谢谢.

推荐答案

for (int i = 0; i < size; i++)
{
    for (int j = i + 1; j < size; j++)
    {
        if (array[i] == array[j])
        {
            array[i - 1 ] = array[i]; /* WRONG! array[-1] = something */
            size--;
        }
    }
}

如果array[0]array[1]相等,array[0-1] = array[0],意思是array[-1] = array[0].你不应该访问 array[-1].

If array[0] and array[1] are equal, array[0-1] = array[0], meaning that array[-1] = array[0]. You are not supposed to access array[-1].

相关文章