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

后端 未结 12 1412
梦如初夏
梦如初夏 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:05

    Indeed, the fastest and as far I can see most elegant method is as advised above:

    std::vector tUserNumbers;
    // ...
    std::set tSet(tUserNumbers.begin(), tUserNumbers.end());
    std::vector(tSet.begin(), tSet.end()).swap(tUserNumbers);
    

    It is O(n log n). This however does not make it, if the ordering of the numbers in the input array needs to be kept... In this case I did:

        std::set tTmp;
        std::vector::iterator tNewEnd = 
            std::remove_if(tUserNumbers.begin(), tUserNumbers.end(), 
            [&tTmp] (int pNumber) -> bool {
                return (!tTmp.insert(pNumber).second);
        });
        tUserNumbers.erase(tNewEnd, tUserNumbers.end());
    

    which is still O(n log n) and keeps the original ordering of elements in tUserNumbers.

    Cheers,

    Paul

提交回复
热议问题