Rıfat Tolga Kiran
Rıfat Tolga Kiran

Reputation: 347

About set container

std::set<int, std::less_equal<int>> myset = {1,1,7,8,2,2};
myset.insert(99);
myset.insert(99);
for(const int & val : myset)
    std::cout << val << " ";

output:

1 1 2 2 7 8 99 99 

Hello, while i was studying on containers. i realized that when i use less_equal function, standart set container behaves just as a multiset container. Is this normal? if it is, what is the difference between multiset and set?

Upvotes: 3

Views: 99

Answers (3)

dascandy
dascandy

Reputation: 7302

Set, map, multiset, multimap et al. require that you provide a total ordering function. A total order means that for any two items, either

  • A op B returns true and B op A returns false - A is less.
  • A op B returns false and B op A returns true - B is less.
  • A op B returns false and B op A returns false - they're equal.

There may not be any values where it returns true for both variants. std::less_equal does not meet this; so the container behaves in some undefined way.

Consider this equivalent to sitting on your couch legs up. It wasn't designed to do that. It may have some result that looks sort of OK, but don't count on it to keep working that way.

Upvotes: 2

MRB
MRB

Reputation: 3822

When you use std::less_equal<int> you sort your container with <=. When you insert the second 99 the set runs through its internal data structures looking for the place to insert 99. It has to check to see if the same value exist. The definition of "the same" for associative containers is equivalence. equivalence means container use !(a <= b) && !(b <= a) to check if two item has same value. If you replace a and b with corresponding value you will get: !(99 <= 99) && !(99 <= 99) => !(true) && !(true) => false && false => false. So you can't use less_equal for associative containers.

Upvotes: 3

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

Is this normal?

No, it is not normal. Your cannot specify std::less_equal as a comparator for std::set because it does not satisfy the strict weak ordering rules.

See the requirements here.

Upvotes: 4

Related Questions