确定向量中是否有重复项 [英] Determine if there are duplicates in vector

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

问题描述

我想确定向量中是否存在重复项.这里最好的选择是什么?

I would like to determine if there are duplicates in a vector. What is the best option here?

sort(arrLinkToClients.begin(), arrLinkToClients.end(), [&](const type1& lhs,const type1& rhs)
{
    lhs.nTypeOfLink < rhs.nTypeOfLink;
});

auto it = unique(arrLinkToClients.begin(), arrLinkToClients.end(), [&](const type1& lhs, const type1& rhs)
{
    lhs.nTypeOfLink == rhs.nTypeOfLink;
});

//how to check the iterator if there are duplicates ?
if (it)
{
  //
}

推荐答案

最好的"选项不存在.这取决于您如何定义最佳".

The "best" option does not exist. It depends on how you define "best".

这里有一些解决方案,每个都有自己的优点和缺点:

Here are some solutions, each with their own advantages and disadvantages:

template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
    std::unordered_map<T, int> m;

    for (const auto& e : v)
    {
        ++m[e];

        if (m[e] > 1)
            return true;
    }
    return false;
}

使用集合

template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
    std::unordered_set<int> s;
    std::copy(v.begin(), v.end(), std::inserter(s, s.begin());
   
    return v.size() != s.size();
}

使用排序和相邻查找(变异范围)

template <class T>
auto has_duplicates(std::vector<T>& v) -> bool
{
    std::sort(v.begin(), v.end());

    return std::adjacent_find(v.begin(), v.end()) != v.last();
}
   

使用 std::find 手动迭代

template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
    for (auto it = v.begin(); it != v.end(); ++it)
        if (std::find(it + 1, v.end(), *it) != v.end())
            return true;
            
    return false;
}

手动迭代

template <class T>
auto has_duplicates(const std::vector<T>& v) -> bool
{
    for (auto i1 = v.begin(); i1 != v.end(); ++i1)
        for (auto i2 = i1 + 1; i2 != v.end(); ++i2)
            if (*i1 == *i2)
                return true;
    
    return false;
}

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

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