0

I have a set declared with my own comp function:

set<int, my_comp> my_set;

The comparison function uses some data stored elsewhere to decide which int is greater. If said data changes, the order of the elements of the set changes too.

How does set handle that? If I know the relative position of an int may have changed, do I have to remove and reinsert it again?

Details: in particular, my_comp uses the ints as indexs to access a vector and compares the values contained in the vector. Said values are bound to change.

user2460978
  • 735
  • 6
  • 19
  • 1
    There's no simple solution. Even the smallest change to the order may force a tree rebalancing up to the root node, as far as `std::set` can tell. A custom Red-Black tree might save some time by not recycling the memory of the old node, but that's it. – MSalters Oct 01 '13 at 23:11

1 Answers1

1

No, the strict weak order must not change for elements in a std::set, the key must be treated as const.

The comparison function must be a model of strict weak ordering:

A strict weak ordering has the following properties. For all x, y, and z in S,

  • For all x, it is not the case that x < x (irreflexivity).
  • For all x, y, if x < y then it is not the case that y < x (asymmetry).
  • For all x, y, and z, if x < y and y < z then x < z (transitivity).
  • For all x, y, and z, if x is incomparable with y, and y is incomparable with z, then x is incomparable with z (transitivity of incomparability).

A better solution would perhaps be a sorted std::vector, together with std::sort (to sort it), std::lower_bound (to find and insert elements), std::inplace_merge (to insert elements).

dalle
  • 18,057
  • 5
  • 57
  • 81
  • I guess the comparison function is only used when inserting and removing elements. Therefore, can I still use a set, but reposition elements manually by removing and reinserting them again? – user2460978 Oct 01 '13 at 20:29
  • With a vector I would have linear time to reposition elements. I need the logarithmic costs of the set. – user2460978 Oct 01 '13 at 20:41
  • How many elements are we talking of? The relocation of the elements in a `std::vector` isn't that slow. – dalle Oct 01 '13 at 21:11
  • 1
    @user2460978: I would have to check to be 100% certain, but I believe other operations could need it too. As an obvious example, locating elements in the set. – MSalters Oct 01 '13 at 22:04
  • @dalle: 100 to 300. But it's an extremely critical operation. – user2460978 Oct 01 '13 at 23:00
  • @MSalters: you are right! I will keep that in mind. My intention now is to keep the set consistent by removing and reinserting the elements whose 'greatness' might have changed. – user2460978 Oct 01 '13 at 23:00