删除 C++ 向量中的重复条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16476099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove Duplicate Entries in a C++ Vector
提问by Jarrod Cabalzar
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 :)
只想删除重复项。池是,vector<pair<string, int>>
但我似乎以某种方式错过了向量开头的一些元素。任何人都可以验证删除的逻辑吗?谢谢 :)
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;
}
采纳答案by Gisway
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):
因为在删除一个元素后,j 指向的位置将跳过一个元素,因为 for 循环中的 j++。根据您的代码解决问题的最简单方法是在 generation.erase(iter) 之后添加 j--:
generation.erase(iter);
j--;
回答by juanchopanza
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";
}