Wednesday 25 January 2017

c++ - operator() overloading for structure



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.


Answer



Try making the comaprison const:



struct index{

int x;
int y;
int z;
bool operator<(const index &b) const
//^^^^^ Missing this,

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...