1) you loop through the x values using the row value when it should be using ncols, vice versa with y, and you should be going in column major in general if you want your code to be 100x more faster (but that is only for simple memory access time, it would be shadowed by how long it takes to print information to cout).
2) you are using uninitialized value y, which "should" be caught by compiler warnings.
3) you are subtracting x by 1 when x is zero on line 29, which "should" be caught by compiler warnings.
4) I don't see where you try to read the file into the array, or generate any sort of data.
5) you are printing the peak every time the peak is overridden, when you probably want just the peak, so use a variable, also the extra endl doesn't make sense.
6) cstring and cmath are unused.
7) are you sure the name "peak" is the best name for an array? considering you are probably gonna want to store your peak variable somewhere?
warnings from web compilers I used:
gcc cpp.sh
(skipping VLA warning)
In function 'int main()': 29:21: warning: array subscript is above array bounds [-Warray-bounds] 29:36: warning: array subscript is above array bounds [-Warray-bounds] 30:38: warning: array subscript is above array bounds [-Warray-bounds] |
msvc rextester.com
(modified to not use a VLA)
Suprisingly gcc doesn't find the uninitialized value, but msvc does, while it doesn't find the out of bounds warning...
source_file.cpp(29) : warning C4700: uninitialized local variable 'y' used
/LIBPATH:C:\boost_1_60_0\stage\lib
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64 |
If I were you I would first fix the problems I mentioned, and stop using the C interface and use vectors at() function to find future 'out of bound' errors, and treating a vector as a 2d array using 1 block of memory using the math:
y*cols + x
, which could be hand written or put in a function/macro/class, and this has the benefit of dynamic size which is convenient.
But that doesn't solve your problem since you are reading a 2d array to find a peak of the whole array instead of row by row, so whats the point of a 2d array when you can just read it as a 1d array. You might not even need a for loop if you want to use <algorithm>'s
std::max_element
function.