| parham93 (2) | |
|
i want to write a function that would go through an array and see if all of its elements are the same. We return true iff all the elements in the array are different from every other element. Let’s say that if the array has 0 elements, then all the elements are different. For instance, allDifferent( {1, 5, 3, 5, 2}, 5 ) would false For instance, allDifferent( {1, 5, 3, 80000, 2}, 5 ) would return true here is my code but something is wrong with it. i would appreciate corrections and instructions on making my code more efficient bool allsame ( const unsigned a[], unsigned elements) { int count=0; for ( int index=0; index < elements; index++) if( a[index]== a[index+1] ) count++; if ( count==0 ) return true; else return false; } | |
|
|
|
| JLBorges (1752) | |||
> if( a[index]== a[index+1] )The last time through the loop, index == (elements-1), and a[index+1] leads to undefined behaviour.
| |||
|
|
|||
| arzhon (5) | |||
If I correctly understand what you meant, maybe this will help
| |||
|
|
|||