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

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

    I think @Michael Jaison G's solution is really brilliant, I modify his code a little to avoid sorting. (By using unordered_set, the algorithm may faster a little.)

    template 
    bool isDuplicated(Iterator begin, Iterator end) {
        using T = typename std::iterator_traits::value_type;
        std::unordered_set values(begin, end);
        std::size_t size = std::distance(begin,end);
        return size != values.size();
    }
    

提交回复
热议问题