Error using custom operator< with std::less

I am trying to overload the < operator, but running into a problem.

Here is my implementation:

int Vector3D::operator < (const Vector3D &vector)
{
   if(x<vector.x)
       return 1;
   else
       return 0;
}

I am calling it using this code:

std::map<Vector3D, std::vector<const NeighborTuple *> > position; 
std::set<Vector3D> pos; 
for (NeighborSet::iterator it = N.begin(); it != N.end(); it++)
{
    NeighborTuple const  &nb_tuple = *it;

    Vector exposition;
    pos.insert (exposition);
    position[exposition].push_back (&nb_tuple);
}

But I get this error:

/usr/include/c++/4.1.2/bits/stl_function.h: In member function 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = ns3::Vector3D]':
/usr/include/c++/4.1.2/bits/stl_map.h:347: instantiated from '_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = ns3::Vector3D, _Tp = std::vector<const ns3::olsr::NeighborTuple*, std::allocator<const ns3::olsr::NeighborTuple*> >, _Compare = std::less<ns3::Vector3D>, _Alloc = std::allocator<std::pair<const ns3::Vector3D, std::vector<const ns3::olsr::NeighborTuple*, std::allocator<const ns3::olsr::NeighborTuple*> > > >]'
../src/routing/olsr/olsr-routing-protocol.cc:853: instantiated from here
/usr/include/c++/4.1.2/bits/stl_function.h:227: error: passing 'const ns3::Vector3D' as 'this' argument of 'int ns3::Vector3D::operator<(const ns3::Vector3D&)' discards qualifiers


The error

passing 'const ns3::Vector3D' as 'this' argument of 'int ns3::Vector3D::operator<(const ns3::Vector3D&)' discards qualifiers

indicates that your operator< does not make the promise that the comparison won't modify the left-hand argument, whereas the map requires that the comparison operation shouldn't modify anything and is trying to use this operator for a constant instance (the map stores the key-types as const objects).

In short, such operator overloads must not mutate anything, and both operands must be declared const. As you have overloaded this as a member function, you must make the function itself const.

bool operator<(const ns3::Vector3D& rhs) const;

BTW, why don't you return a bool (the result must be true or false)?


Looks like you need to be using const_iterators:

NeighborSet::iterator

should be

NeighborSet::const_iterator

Also if your compiler supports it (C++0x) use cbegin and cend instead of begin and end.

链接地址: http://www.djcxy.com/p/73078.html

上一篇: 为什么使用转换运算符输出类不适用于std :: string?

下一篇: 使用自定义运算符<使用std :: less时出错