Remove Duplicate Entries in a C++ Vector

后端 未结 2 1689
抹茶落季
抹茶落季 2021-02-15 22:58

Just want to remove duplicates. Pool is vector> but I seem to miss some elements at the start of the vector somehow. Can anyone verify

相关标签:
2条回答
  • This is a very common issue.

    Because after you erase an element the position j pointed will skip one element due to the j++ on the for loop. the easiest solution to solve the problem based on your code is to add j-- after generation.erase(iter):

      generation.erase(iter);
      j--;
    
    0 讨论(0)
  • 2021-02-15 23:48

    If you don't mind sorting the vector, then you can use std::unique. That would be O(Nlog(N))

    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    int main() 
    {
        std::vector<int> v{1,2,3,1,2,3,3,4,5,4,5,6,7};
        std::sort(v.begin(), v.end()); 
        auto last = std::unique(v.begin(), v.end());
        v.erase(last, v.end());
        for (const auto& i : v)
          std::cout << i << " ";
        std::cout << "\n";
    }
    
    0 讨论(0)
提交回复
热议问题