Due to software constraints, I cannot use the standard libraries, math.h
, algorithm
, templates, inline, or boost. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.
I need to duplicate the Matlab any function in C / C++ for an array. I currently have written two any functions with different inputs depending on the array size.
- Is it possible to write just one
any
function without using templates? - How can I improve performance?
I am striving for const
correctness, performance/efficiency, and avoiding implicit type casting.
bool any(bool* array, const int N){
// mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
bool val;
val = array[0] == true;
int i = 0;
while (val == false && i < N){
val = array[i++] == true;
}
return val;
}
bool any(bool** array, const int nRow, const int nCol){
// mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
bool val;
val = array[0][0] == true;
int i = 0;
while (i < nRow && val == false){
int j = 0;
while (j < nCol && val == false){
val = array[i][j++] == true;
}
i++;
}
return val;
}
const int N
should be asize_t
\$\endgroup\$ – Elpezmuerto Oct 4 '11 at 19:06== true
to convert a bool to a bool, then remember that the result is still a bool. Therefore, you should writeval = (array[0] == true) == true;
. Or maybe justval = array[0]
. \$\endgroup\$ – Mike Seymour Oct 5 '11 at 13:24