删除c++向量中的重复项

时间:2021-07-11 00:15: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是向量 >但我似乎在向量的开头漏掉了一些元素。有人能证实移除的逻辑吗?谢谢:)

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 个解决方案

#1


4  

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):

因为在删除一个元素之后,由于for循环上的j+, j指向的位置将跳过一个元素。根据你的代码来解决这个问题最简单的方法是添加j——生成后。

  generation.erase(iter);
  j--;

#2


19  

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

如果您不介意对向量排序,那么您可以使用std::unique。这将是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";
}

#1


4  

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):

因为在删除一个元素之后,由于for循环上的j+, j指向的位置将跳过一个元素。根据你的代码来解决这个问题最简单的方法是添加j——生成后。

  generation.erase(iter);
  j--;

#2


19  

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

如果您不介意对向量排序,那么您可以使用std::unique。这将是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";
}