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

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

    //std::unique(_copy) requires a sorted container.
    std::sort(cont.begin(), cont.end());
    
    //testing if cont has duplicates
    std::unique(cont.begin(), cont.end()) != cont.end();
    
    //getting a new container with no duplicates
    std::unique_copy(cont.begin(), cont.end(), std::back_inserter(cont2));
    

提交回复
热议问题