如何解决此编译错误 [英] How do I resolve this compilation error

查看:92
本文介绍了如何解决此编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您已获得一个大小为N的整数数组A.数组的每个元素的范围都在1到10 ^ 5之间。您需要找到数组中每个不同元素的频率。元素需要以递增的顺序存在于输出中。你需要打印每个不同元素的值和频率。

You have been given an integer array A of size N. Each element of the array ranges between 1 and 10^5. You need to find the frequency of each distinct element of the array. The elements need to be present in the output in ascending order. You need to print the value and then frequency of each distinct element.

->I am getting this error
  Command failed: ./a.out <input2.txt
Segmentation fault





我的尝试:





What I have tried:

#include <iostream>
using namespace std;

void InsertionSort(int *arr,int n){
  int key,j=0;
  for(int i=1;i<n;i++){
    key = arr[i];
    j = i-1;
    while(j>=0 && key <arr[j]){
      arr[j+1] = arr[j];
      j = j-1;
    }
    arr[j+1] = key;
  }
}

void FrequencyAndPrint(int *arr,int n){
  int temp;
  int freq ;
  int j=0;
  for(int i=0;i<n;i++){
    temp = arr[i];
    freq = 1;
    for( j=i+1;j<n;j++){
      if(temp == arr[j])
      ++freq;
      else 
        break;
    }
    i = j-1;
    cout<<arr[i]<<" "<<freq<<endl;
  }
  return;
}

int main()
{
	int N;
  int arr[10];
  cin>>N;
  for(int i=0;i<N;i++){
    cin>>arr[i];
  }
  InsertionSort(arr,N);
  FrequencyAndPrint(arr,N);

	return 0;
}

推荐答案

您正在使用固定数组,因此如果N大于10,结果很可能是SEGV故障。在第一次接受N的值后,应该使用 new 语句分配数组。例如:

You are using a fixed array, so if N is greater than 10 the result will most likely be a SEGV fault. You should allocate the array with the new statement after you have first accepted the value of N. Something like:
int N;

cin >> N;
int* arr = new int[N];
for(int i=0; i < N; i++)
{
    cin >> arr[i];
}



您还需要检查输入文件的内容以确保其中包含有效数据。


You also need to check the contents of your input file to make sure it contains valid data.


这篇关于如何解决此编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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