Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 547
Yotam Avatar asked Feb 16 '26 13:02

Yotam


1 Answers

Try making the comaprison const:

struct index{
  int x;
  int y;
 int z;
  bool operator<(const index &b) const
                               //^^^^^ Missing this,
like image 56
Martin York Avatar answered Feb 19 '26 01:02

Martin York



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!