Using a function to remove duplicates from an array in C++(使用函数从 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++ 中的数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用函数从 C++ 中的数组中删除重复项


- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01