使用函数从 C++ 中的数组中删除重复项 [英] Using a function to remove duplicates from an array in C++

查看:30
本文介绍了使用函数从 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].

这篇关于使用函数从 C++ 中的数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆