0

This code gives me an error and i really dont know why, please help :)

The input is a 2d array and i want to see how many times each element appears, for storing the value and the number count i use a 2d array that acts like a list, v[i][0] being the value and v[i][1] being the count for that value #include <iostream> #include <fstream> using namespace std; ifstream in("k.in"); ofstream out("k.out"); int main() { int n,m,ii=1; in>>n>>m; int arr[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) in>>arr[i][j]; int v[n*m][2]; for(int i=0;i<n*m;i++) v[i][0]=0,v[i][1]=0; v[0][0]=arr[0][0]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) for(int l=0;l<ii;l++) if(arr[i][j]==v[l][0])v[l][1]++; else v[ii][0]=arr[i][j],v[ii][1]=1,ii++; for(int i=0;i<ii;i++) out<<v[i][0]<<' '<<v[i][1]<<endl; return 0; }

2nd Feb 2017, 7:37 PM
Catalin Dervesteanu
Catalin Dervesteanu - avatar
5 Respostas
+ 3
Are you trying to run it in SoloLearn Code Playground? Because you are trying to handle files ( "k.in" and "k.out" ), and you cannot do that with the distant compiler of Sololearn ^^
3rd Feb 2017, 3:08 AM
visph
visph - avatar
+ 3
Doesn't the two lines with ifstream and ofstream declaration need to be in the main() block? ( I have very few experience with c++, almost none with handling files ^^ )
3rd Feb 2017, 6:23 AM
visph
visph - avatar
+ 3
I think I get it ^^ Nested loops for doing count is buggy: you iterate over length of the 'v' array to verify if the actual value is already registered, and add a new element to it if actual value is different of EACH values already registered... To fix it, do that: int f; for(int i=0;i<n;i++) for(int j=0;j<m;j++) { f=-1; for(int l=0;l<ii;l++) if(arr[i][j]==v[l][0]) { f=l; break; } if (f!=-1) v[f][1]++; else v[ii][0]=arr[i][j],v[ii][1]=1,ii++; } For information, to debug it, I replaced all file in/out by console in/out, and add a lot ( progressivly ) of console output to log and verify that each arrays, variables, have expected values... So I noticed that 'v' array was too much growing, and 'ii' index overflow 'n*m', so all breaks without output ^^
3rd Feb 2017, 7:29 AM
visph
visph - avatar
+ 1
I'm not trying in sololearn :/
3rd Feb 2017, 6:17 AM
Catalin Dervesteanu
Catalin Dervesteanu - avatar
0
the file declaration doesn't need to be inside the main
3rd Feb 2017, 6:32 AM
Catalin Dervesteanu
Catalin Dervesteanu - avatar