How do I use the following struct:
struct point
{
int x;
int y;
int z;
};
as a key for std::map
Of course, boost::tuple would make this utterly unnecessary.
Update Adding the all-inclusive have-your-cake-and-eat-it-too no-drawback solution here. IMHO it rocks!
#include
struct point
{
int x, y, z;
point(int x, int y, int z) : x(x), y(y), z(z) {}
bool operator<(const point& rhs) const
{
return boost::tie(x, y, z) < boost::tie(rhs.x, rhs.y, rhs.z);
}
};
Here is the kicker: it all optimizes away. Compile:
int main()
{
point a(1,2,3), b(3,2,1);
bool lt = a
With g++ -O2 yields the following in assembly.
main:
.LFB1132:
pushl %ebp
xorl %eax, %eax
movl %esp, %ebp
popl %ebp
ret
.LFE1132:
The compiler was able to optimize the whole of this program to ... return 0 effectively. That is pretty neat.
Here goes the simple answer:
struct point
{
point(int x, int y, int z)
: x(x), y(y), z(z) {}
int x;
int y;
int z;
bool operator<(const point& rhs) const
{
if (x
Also, I would consider looking for a redefinition of my struct that will allow using std::lexicographical_compare
#include
// ...
bool operator<(const point& rhs) const
{
return std::lexicographical_compare(&xyz, &xyz+3, &rhs.xyz, &rhs.xyz+3);
}