c++ program


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;



}
> if( a[index]== a[index+1] )

The last time through the loop, index == (elements-1), and a[index+1] leads to undefined behaviour.

1
2
3
4
5
6
7
8
9
bool all_same( const unsigned int a[], unsigned int n )
{
    if( n < 2 ) return true ;

    for( unsigned int i = 0 ; i < (n-1) ; ++i )
        if( a[i] != a[i+1] ) return false ;

    return true ;
}
If I correctly understand what you meant, maybe this will help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool allsame ( const unsigned a[], unsigned elements){
      int count=0;

      for (int index=0; index<elements; index++){

            for(int x=0;x<elements;x++){

                  if(index!=x && a[index]==a[x]){
                        return false;
                  }

            }

      }
      
      return true;

}
Topic archived. No new replies allowed.