C++ Multiset count()

527 views Asked by At

So the problem is the following, I have a multiset where I use the std::equal_to operator for comparing the elements, but when I use the count() method it says all 4 elements in my multiset are equal_to my counts parameter.

std::multiset< std::string, std::equal_to< std::string > > mset;
mset.insert("C++");
mset.insert("SQL");
mset.insert("Jav");
mset.insert("C");

for(std::multiset<std::string>::iterator it = mset.begin(); it != mset.end(); ++it){
std::cout << *it << std::endl;
}

std::cout << std::endl;
std::cout << mset.count("STR");

The output is : 4

If i understand right whats happening is "STR"=="C++"=="SQL"=="Jav"=="C"==true. And this is what I don't understand.

Thankyou for the help.

2

There are 2 answers

0
alain On

As BobTFish already said in a comment, the Compare type of std::multiset should return true if the first argument is "less" (has to be ordered before) the second argument. The default type is std::less<Key>.

0
ks1322 On

For elements stored in std::multiset you must define strict weak ordering relation f(x, y). One of the properties of strict weak ordering is Irreflexivity, that is f(x, x) must be false. This property is violated in your strict weak ordering and you have got some undefined results.

What you probably want is to use std::unordered_multiset instead.