删除C ++向量中的重复条目 [英] Remove Duplicate Entries in a C++ Vector

查看:173
本文介绍了删除C ++向量中的重复条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只想移除重复的项目。池是矢量<对<字符串,int>> 但我似乎错过了一些元素在矢量的开始不知何故。任何人都可以验证删除的逻辑?感谢:)

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;
}


推荐答案

这是一个很常见的问题。

This is a very common issue.

因为在删除一个元素后,j指向的位置将跳过一个元素,这是由于for循环中的j ++。
解决基于你的代码的问题的最简单的解决方案是在generation.erase(iter)之后添加j--

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--;

这篇关于删除C ++向量中的重复条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆