Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

c++ - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...