2
votes

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.

2
Where are you getting the compile error? - Luchian Grigore
That error doesn't mean that you need to overload operator(). - Robᵩ
@LuchianGrigore At the first time I use the [] operator with the index - Yotam
More context. You gave the line that was generating the error but not the error message itself. But I am guessing it is because you have no declared the comparison const. - Martin York
@LokiAstari What is a comparison const? Google doesn't give a naive result when I search this... - Yotam

2 Answers

10
votes

Try making the comaprison const:

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

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;
    }
}