- Implemented addition-subtraction swap. Unlike the most obvious solution — XOR swap — it works with double.
- In Igloo, it's advisable to compare doubles using EqualsWithDelta in lieu of Equals.
#include <algorithm> #include <math.h> template< class T > void Swap( T& a, T& b ) { a = a + b; b = a - b; a = a - b; }
- #include <algorithm>
- #include <math.h>
- template< class T >
void Swap( T& a, T& b ) { std::swap( a, b ); }- void Swap( T& a, T& b )
- {
- a = a + b;
- b = a - b;
- a = a - b;
- }
Describe(Tests) { It(Swaps) { int a = 1, b = 2; bool c = true, d = false; double e = 3.14, f = 6.28; Swap( a, b ); Swap( c, d ); Swap( e, f ); Assert::That( a, Equals(2)); Assert::That( b, Equals(1)); Assert::That( c, Equals(false)); Assert::That( d, Equals(true)); Assert::That( e, EqualsWithDelta(6.28, 0.1)); Assert::That( f, EqualsWithDelta(3.14, 0.1)); } };
- Describe(Tests)
- {
- It(Swaps)
- {
- int a = 1, b = 2;
- bool c = true, d = false;
- double e = 3.14, f = 6.28;
- Swap( a, b );
- Swap( c, d );
- Swap( e, f );
- Assert::That( a, Equals(2));
- Assert::That( b, Equals(1));
- Assert::That( c, Equals(false));
- Assert::That( d, Equals(true));
Assert::That( e, Equals(6.28));Assert::That( f, Equals(3.14));- Assert::That( e, EqualsWithDelta(6.28, 0.1));
- Assert::That( f, EqualsWithDelta(3.14, 0.1));
- }
- };