More elegant way to check for duplicates in C++ array?

后端 未结 12 1434
梦如初夏
梦如初夏 2020-12-01 09:36

I wrote this code in C++ as part of a uni task where I need to ensure that there are no duplicates within an array:

// Check for duplicate numbers in user in         


        
12条回答
  •  醉话见心
    2020-12-01 10:12

    #include
    #include
    
    int main(){
    
        int arr[] = {3, 2, 3, 4, 1, 5, 5, 5};
        int len = sizeof(arr) / sizeof(*arr); // Finding length of array
    
        std::sort(arr, arr+len);
    
        int unique_elements = std::unique(arr, arr+len) - arr;
    
        if(unique_elements == len) std::cout << "Duplicate number is not present here\n";
        else std::cout << "Duplicate number present in this array\n";
    
        return 0;
    }
    

提交回复
热议问题