简体   繁体   English

C++ 检查数组是否包含重复项

[英]C++ check if the array contains duplicates

I have vector of strings, and I need to check if the array contains duplicates:我有字符串向量,我需要检查数组是否包含重复项:

std::vector<std::string> data{};
const bool notContainsDuplicates = ...;

Can I solve this problem with standard library?我可以用标准库解决这个问题吗?

You can do it like this, using a standard library set to count the number of unique entries, if this is the same as the length of the input array there are no duplicates (another option is to use an unordered_map):您可以这样做,使用标准库集来计算唯一条目的数量,如果这与输入数组的长度相同,则没有重复项(另一种选择是使用 unordered_map):

#include <cassert>
#include <string>
#include <vector>
#include <set>

bool contains_duplicates(const std::vector<std::string>& input)
{
    std::set<std::string> set{ input.begin(), input.end() };
    return (set.size() != input.size());
}

int main()
{
    std::vector<std::string> no_dups{ "hello","this","does","not","contain","duplicates" };
    std::vector<std::string> dups{ "hello","this","does","contain","duplicates","hello","this" };

    assert(!contains_duplicates(no_dups));
    assert(contains_duplicates(dups));

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM