0

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?

5
  • 2
    Can I solve this problem with standard library? Probably yes, but not sure what is your end goal or actual requirement. Commented Jan 26, 2022 at 14:22
  • Can you sort the vector (or a copy of the vector) first? That would make the job a lot easier. Commented Jan 26, 2022 at 14:24
  • 2
    Does this answer your question? More elegant way to check for duplicates in C++ array? Commented Jan 26, 2022 at 14:25
  • I can't sort and change vector Commented Jan 26, 2022 at 14:28
  • My -1 for you not explaining the problem. Commented Jan 26, 2022 at 15:16

1 Answer 1

3

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) :

#include <cassert>
#include <string>
#include <string_view> // edit : added
#include <vector>
#include <set>

bool contains_duplicates(const std::vector<std::string>& input)
{
    // edit removed : std::set<std::string> set{ input.begin(), input.end() };
    std::set<std::string_view> 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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

std::set<std::string_view> would avoid copying the strings
You could reduce the function to a single line: return std::set<std::string_view>(input.begin(), input.end()).size() != input.size();
@AlanBirtles A thanks for that feedback didn't think of that. But it sure would be an improvement.
Edit : Added the string_view solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.