问题描述
我正在编写一个程序,其中有一个用户输入整型数组,调用一个从该数组中删除重复项的函数,然后打印出修改后的数组。当我运行它时,它允许我将值输入到数组中,但当我输入值时,会给我一个分段错误错误消息。
这是我的代码:
#include< iostream>
使用namespace std;
void rmDup(int array [],int& size)
{
for(int i = 0; i< size; i ++)
{
for(int j = i + 1; j {
if(array [i] == array [j])
{
array [i - 1] = array [i];
size--;
$ b int main()
{
const int CAPACITY = 100;
int值[CAPACITY],currentSize = 0,输入;
cout<< 请输入一系列最多100个整数,按'q'退出。 (cin>>输入)
{
if(currentSize< CAPACITY)
{
values [currentSize] = input;
currentSize ++;
}
}
rmDup(values,currentSize);
for(int k = 0; k {
cout<值[K];
}
返回0;
}
谢谢。
for(int i = 0; i< size; i ++)
$ b {
for(int j = i + 1; j {
if(array [i] == array [j])
{
array [i - 1] = array [i]; / *错误! array [-1] = something * /
size--;
如果 array [0]
和 array [1]
是相等的, array [0-1] = array [0]
,意味着数组[-1] =数组[0]
。你不应该访问数组[-1]
。
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?
Here is my code:
#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;
}
Thank you.
解决方案 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--;
}
}
}
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 ++数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!