c++arrayssortedlist

Find unique element in sorted array using c++


I am trying to find unique element from the array these is question

Input  : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output : arr[] = {1, 2, 3, 4, 5} 

They give me correct output but why they give 0 at the end in output:

these is my output:
{1,2,3,4,5,0}

Code:

#include<iostream>
using namespace std;
int main(){
    int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
    int n=sizeof(arr)/sizeof(arr[0]);
    int c=0;
    for(int j=0;j<=n;j++){
        if(arr[j]!=arr[j+1]){
            cout<<arr[j];
            }


    }
   
} 

 

Solution

  • Except for std::cout, you code is much more C than ++.

    A more modern solution looks like this:

    #include <iostream>
    #include <algorithm>
    #include <vector>
    int main(){
        std::vector<int> arr {1, 2, 2, 3, 4, 4, 4, 5, 5};
        auto last = std::unique(arr.begin(), arr.end());
        arr.erase(last, arr.end());
        std::for_each(arr.begin(), arr.end(), [](int n){std::cout << n << std::endl;} );
    } 
    

    Try it on Godbolt.