tags:

views:

123

answers:

2

Hi, all

In my previous question you told me I should overload < operator. I tried it and now have another problem with it.

I wrote this simple code in my vector.h file:

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

and the last line of this part of my program calls this function:

/for keepping exposition of a node

std::map<Vector, std::vector<const NeighborTuple *> > position; 
std::set<Vector> 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);
}

and has 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

I'll be thankful if anyone helps me in solving this problem.

Thanks in advance.

Bahar

+1  A: 

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.

DanDan
Thanks so much everyone.:)
bahar
+10  A: 

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

UncleBens