Remove Duplicate Entries in a C++ Vector

2020-06-16 05:57发布

Just want to remove duplicates. Pool is vector<pair<string, int>> but I seem to miss some elements at the start of the vector somehow. Can anyone verify the logic of the removal? Thanks :)

Pool Master::eliminateDuplicates(Pool generation)
{
    for(int i = 0; i < generation.size(); i++)
    {
        string current = generation.at(i).first;

        for(int j = i; j < generation.size(); j++)
        {
            if(j == i)
            {
                continue;
            }
            else
            {
                string temp = generation.at(j).first;
                if(current.compare(temp) == 0)
                {
                    Pool::iterator iter = generation.begin() + j;
                    generation.erase(iter);
                }
            }
        }
    }

    return generation;
}

2条回答
神经病院院长
2楼-- · 2020-06-16 06:26

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";
}
查看更多
一纸荒年 Trace。
3楼-- · 2020-06-16 06:31

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--;
查看更多
登录 后发表回答