I have a std::vector and I want to check all the elements in it. If a certain element appears more than once, I signal an error.
This is how I did it:
std::vector<std::string> test;
test.push_back("YES");
test.push_back("YES");
for(int i = 0; i < test.size(); i++)
{
if(test[i] > 1)
{
DCS_LOG_DEBUG("ERROR WITH COUNT")
}
}
This did not work though I know how to count using the std::vector::count() method. But I want to get the count for each element, as opposed to counting everything… any ideas?
The simplest way is to
std::sortthe vector and then usestd::adjacent_find.However, if you don’t want to sort the vector, you can do something like this in C++11:
This prints:
I didn’t actually benchmark it, but this has a chance for being rather performant, for following reasons:
v.size()when constructingm), so hashtable resizes are minimized.