Reputation: 277
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?
Upvotes: 0
Views: 331
Reputation: 13120
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;
}
Upvotes: 3