简体   繁体   中英

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

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_t s inserted, but in different order, to not evaluate equal?

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.

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_t s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM