确定向量中是否存在重复项

时间:2018-03-13 09:38:45

标签: c++ vector stl unique

我想确定一个向量中是否有重复项。这里最好的选择是什么?

<agm-marker *ngIf="school.lat && school.lng" 
                    [iconUrl]="{url: school.mapMarker, scaledSize: {height: 75,width: 48},labelOrigin:{x:70,y:20}}"
                    [label]="{text:school.schoolName}"
                    [longitude]="school.lng | parseFloat"
                    [latitude]="school.lat | parseFloat">
        </agm-marker>

2 个答案:

答案 0 :(得分:3)

&#34; best&#34;选项不存在。这取决于你如何定义&#34; best&#34;。

以下是一些解决方案,每种解决方案都有各自的优缺点:

Using map
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;
}
Using set
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();
}
Using sort and adjacent_find (mutating range)
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();
}
Manual iteration with 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;
}
Manual iteration
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;
}

答案 1 :(得分:1)

如果没有重复项,则从unique返回的迭代器是结束迭代器。所以:

if (it != arrLinkToClients.end())
    cout << "Some duplicates found!";