Shot in foot

Stupid std::replace() takes references. (And, conveniently, std::min() and std::max() also work over references.)

Always remember to make yourself something that can't be changed when you aren't looking. (Because const only means it if it wants to.)

1
2
// Evil code:
replace( xs.begin(),  xs.end(),  max( xs[a], xs[b] ),  min( xs[a], xs[b] ) );
1
2
3
4
// Less evil code:
int xs_a = min( xs[a], xs[b] );  // (Yep. This was over integers.)
int xs_b = max( xs[a], xs[b] );
replace( xs.begin(), xs.end(), xs_b, xs_a );

Took me half an hour to figure out why my Kruskal MST wasn't working.
:@
const should be renamed readonlyfromthisparticularvariable but programmers are too lazy to type that out.

Also, there's nothing wrong with the behavior of those functions - what if you really did want references to be used and didn't want to deal with the overhead/hassle of a std::reference_wrapper? Copies of primitives are cheap, whereas wrapper classes are not.
Last edited on
Yes, of course. Only it's easy to forget stuff when you're playing with integers.

(The problem was that my head expected min() and max() to return copies of the integers.)
Last edited on
Casting to non-reference type helps too:
1
2
replace( xs.begin(),  xs.end(),  static_cast<int>(max( xs[a], xs[b] )),  min( xs[a], xs[b] ) );
replace( xs.begin(),  xs.end(),  int(max( xs[a], xs[b] )),  min( xs[a], xs[b] ) );
Topic archived. No new replies allowed.