Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting std::set as keys to std::map

Tags:

c++

I am using std::set<std::uint32_t> as keys to a std::map. I have read on cppreference that std::set implements the Compare operation via std::lexicographical_compare of two std::set- what does this actually mean?

Also, is it possible for two std::set with the same std::uint32_ts inserted, but in different order, to not evaluate equal?

like image 783
bricoletc Avatar asked Aug 31 '26 09:08

bricoletc


2 Answers

I have read on cppreference that std::set implements the Compare operation via std::lexicographical_compare of two std::set - what does this actually mean?

It means that the comparison operator of std::set calls std::lexicographical_compare with the range of the elements of the operands as arguments, and returns the result. std::lexicographical_compare compares the lexicographical order of the operand ranges. This is the same order as is used to order words in a dictionary.

Also, is it possible for two std::set with the same std::uint32_ts inserted, but in different order ...

std::set is ordered. All sets with same comparison function have the same order. Elements that compare less are before elements that compare as higher. Thus, if both elements and the comparison function are the same, then the sets will compare equal in lexicographical comparison.

If the comparison function is stateless, then all instances of it produce the same order. In theory, a stateful comparison function could produce a different order for different set. I would recommend to avoid such counter-intuitive comparison functions.

like image 188
eerorika Avatar answered Sep 02 '26 06:09

eerorika


It means what it says - comparing two sets does so lexicographically.

The very same site tells you what that means if you simply click through:

Lexicographical comparison is a operation with the following properties:

  • Two ranges are compared element by element.
  • The first mismatching element defines which range is lexicographically less or greater than the other.
  • If one range is a prefix of another, the shorter range is lexicographically less than the other.
  • If two ranges have equivalent elements and are of the same length, then the ranges are lexicographically equal.
  • An empty range is lexicographically less than any non-empty range.
  • Two empty ranges are lexicographically equal.

Simplified, it basically means an intuitive element-by-element comparison from left-to-right (ref).

As for your second question, the contents of a set<int> are in increasing numerical order, irrespective of what order you inserted the elements, so no.

like image 38
Lightness Races in Orbit Avatar answered Sep 02 '26 06:09

Lightness Races in Orbit