If it is crucial for you to save one byte of four, I'd suggest you to
define a storage-only
type with implicit conversion to and from int:
#include <iostream>
#include <algorithm>
using namespace std;
class int_stump {
char d[3];
public:
// implicit constructor
int_stump(int x = 0) {
// assert (...)
d[0] = x % 0x100; x >>= 8;
d[1] = x % 0x100; x >>= 8;
d[2] = x % 0x100;
}
inline operator int() {
int result = 0;
result += d[2]; result <<= 8;
result += d[1]; result <<= 8;
result += d[0];
return result;
}
};
bool operator < (int_stump a, int_stump b) { return int(a) < int(b); }
// ... and any other int's operator you need implemented in the same manner
int main() {
int_stump arr[10];
arr[1] = arr[0] + 5;
arr[2] = 7 + 9;
arr[3] = arr[1] + arr[2];
sort(arr, arr + 10);
cout << sizeof(arr) << endl;
for (int i = 0; i < 10; ++i) cout << arr[i] << endl;
}
This outputs:
30
0
...
5
16
21
This way is rather easy to implement, doesn't require so thorough
testing and relies on hardware operations.
It still incurs some overhead on conversion, so you may speed up the
conversion in a platform-dependent
way by using an old trick with unions like:
union conversion_trick_u {
int a;
char c[4];
};
The conversion will be equivalent to copying 7 bytes and no arithmetics.
Best regards!
2012/3/3 bugos <[email protected]>:
> Hello,
> is there a way to define my own data type, which will be idetical to
> an int, but just 3 bytes size? i must be able to use it as an int and
> even use std::sort() with it.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Google Code Jam" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected].
> For more options, visit this group at
> http://groups.google.com/group/google-code?hl=en.
>
--
You received this message because you are subscribed to the Google Groups
"Google Code Jam" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/google-code?hl=en.