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

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

    You could sort the array in O(nlog(n)), then simply look until the next number. That is substantially faster than your O(n^2) existing algorithm. The code is also a lot cleaner. Your code also doesn't ensure no duplicates were inserted when they were re-entered. You need to prevent duplicates from existing in the first place.

    std::sort(userNumbers.begin(), userNumbers.end());
    for(int i = 0; i < userNumbers.size() - 1; i++) {
        if (userNumbers[i] == userNumbers[i + 1]) {
            userNumbers.erase(userNumbers.begin() + i);
            i--;
        }
    }
    

    I also second the reccomendation to use a std::set - no duplicates there.

提交回复
热议问题