1

Since std::set is implemented as a binary tree, how does it compare std::string for inequality? Does it look like a < b && b < a?

Is it using the length of the string directly or is it hashing it somehow? Does it at all guarantee uniqueness of strings?

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Lev
  • 1,698
  • 3
  • 18
  • 26

2 Answers2

5

It simply does less twice - swapping left and right for the second comparison. If both return false, strings are considred to be equal.

And yes, it does guarantee uniqueness of it's members (including strings) as long as operator less is doing what it is expected to do for member types (which is of course true for strings, but might be not so true for user-defined types).

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • It cannot guarantee uniqueness. It can only guarantee *equivalence* as far as the comparison operator provided is concerned. For `std::set` this implies that equivalence implies equality of the string content, but not of the amount of allocated memory, for example. – Walter Nov 10 '15 at 19:40
  • @Walter i don't understand this.. Could you give an example where an element appears twice in a set? Are you saying that if the allocated memory is different then you could manage to do that? I must be missing something I guess.. – dingalapadum Nov 10 '15 at 19:47
  • @Walter Of course it is guaranteeing equivalence, that's what you want. You don't (by default) want a string to show up twice in a set just because the amount of memory used to store its information is different. If you do want such behaviour then you just specify a different comparison function to use to `std::set`. – SirGuy Nov 10 '15 at 19:52
  • @Walter Equality is a type of equivalence, and people (technically incorrectly) use equality where they really mean equivalence. I don't think it's much of a problem in most cases. – SirGuy Nov 10 '15 at 19:53
  • @dingalapadum I never said an element can appear twice in a set. But two elements that you think are different may be considered equivalent if they compare equal (depending on the comparison functor). – Walter Nov 10 '15 at 21:12
  • @Walter if an element can't appear twice in a set, isn't it then unique in the set? And if every element can appear at most once, isn't that a guarantee of uniqueness in the set? I think the set *does* provide uniqueness.... Or is this a discussion about 'equality'? Ok then: so what does 'equal' mean to you in this context? – dingalapadum Nov 11 '15 at 00:49
2

std::set uses less to sort its keys. That's operator< on a std::string which compares the strings lexicographically.

dingalapadum
  • 2,077
  • 2
  • 21
  • 31
Anon Mail
  • 4,660
  • 1
  • 18
  • 21