删除字符串向量中的重复项 [英] Removing duplicates in a vector of strings

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

问题描述

我有一个向量字符串:

std::vector<std::string> fName

包含文件名列表< a,b,c,d,a,e,e,d,b> .

我想删除所有重复的文件,并只保留向量中没有重复的文件.

I want to get rid of all the files that have duplicates and want to retain only the files that do not have duplicates in the vector.

for(size_t l = 0; l < fName.size(); l++)
{
    strFile = fName.at(l);
    for(size_t k = 1; k < fName.size(); k++)
    {
        strFile2 = fName.at(k);
        if(strFile.compare(strFile2) == 0)
        {
            fName.erase(fName.begin() + l);
            fName.erase(fName.begin() + k);
        }
    }
}

这将删除一些重复项,但是仍然有一些重复项,需要帮助进行调试.

This is removing a few of the duplicate but still has a few duplicates left, need help in debugging.

我的输入看起来也像< a,b,c,d,e,e,d,c,a> 并且我的预期输出是< b> 由于所有其他文件b,c,d,e都具有重复项,因此将其删除.

Also my input looks like <a,b,c,d,e,e,d,c,a> and my expected output is <b> as all other files b,c,d,e have duplicates they are removed.

推荐答案

#include <algorithm>

template <typename T>
void remove_duplicates(std::vector<T>& vec)
{
  std::sort(vec.begin(), vec.end());
  vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
}

注意:这要求T定义了 operator< operator == .

Note: this require that T has operator< and operator== defined.

为什么起作用?

std :: sort 使用小于比较运算符对元素进行排序

std::sort sort the elements using their less-than comparison operator

std :: unique 删除重复的连续元素,并使用相等的元素进行比较比较运算符

std::unique removes the duplicate consecutive elements, comparing them using their equal comparison operator

如果我只想要唯一元素怎么办?

那么您最好使用std :: map

Then you better use std::map

#include <algorithm>
#include <map>

template <typename T>
void unique_elements(std::vector<T>& vec)
{   
  std::map<T, int> m;
  for(auto p : vec) ++m[p];
  vec.erase(transform_if(m.begin(), m.end(), vec.begin(),
                         [](std::pair<T,int> const& p) {return p.first;},
                         [](std::pair<T,int> const& p) {return p.second==1;}),
            vec.end());
}

请参阅:此处.

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

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