Specific element
Count is the standard way to go:
#include <algorithm>
...
if (count (test.begin(), test.end(), "YES") > 1)
std::cerr << "positive\n";
If you need more performance, you can do it the classic way:
bool exists = false;
for (auto const& v : test) {
if (v == "YES") {
if (exists) {
std::cerr << "positive\n";
break;
}
else exists = true;
}
}
Any element multiple times
For large vectors, try std::set
:
std::set<std::string> exists;
for (auto const &v : test) {
if (!exists.insert(v).second)
std::cerr << "positive\n";
}
In this approach, if you also want to be able to recognize whether you already mentioned its non-uniqueness, you may want to use std::multiset
:
const std::multiset<std::string> counts (test.begin(), test.end());
for (auto const &v: test)
if (counts.count (v) == 2) std::cerr << "meh\n";
If the container is small, and you just want to see if any element is there more than once:
auto multitimes = [&test] (std::string const &str) {
return count(test.begin(),test.end(),str)>1;
};
if (any_of (test.begin(), test.begin(), multitimes))
std::cerr << "something was there more than once\n";