Reputation: 10695
I'm trying to use a structure for my map in c++. The structure is simple:
struct index{
int x;
int y;
int z;
bool operator<(const index &b){
bool out = true;
if ( x == b.x ){
if ( y == b.y ){
out = z < b.z;
} else out = y < b.y;
} else out = x < b.x;
return out;
}
};
But when I compile I get an error:
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h: In member function 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = membrane::index]': /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_map.h:347: instantiated from '_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = membrane::index, _Tp = std::set, std::less >, std::allocator > >, _Compare = std::less, _Alloc = std::allocator, std::less >, std::allocator >
]' memMC.cpp:551: instantiated from here
Which, as far as I can tell, means that I need to overload the () operator. However I don't know what this operator usually do so I don't know how to overwrite it correctly. Wikipedia tells me that this is a cast operator but I don't think they return bool...
The compiler crush at the first time I try to access a map element using [] operator.
Upvotes: 2
Views: 6217
Reputation: 3510
Try a free overload:
bool operator < (const index &a, const index &b)
{
if (a.x == b.x)
{
if (a.y == b.y)
{
return a.z < b.z;
}
else
{
return a.y < b.y;
}
}
else
{
return a.x < b.x;
}
}
Upvotes: 4
Reputation: 264749
Try making the comaprison const:
struct index{
int x;
int y;
int z;
bool operator<(const index &b) const
//^^^^^ Missing this,
Upvotes: 10