what is wrong with the codes below?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Peer
{
   int p_id;
  public:
    Peer(int id):p_id(id){}
    int id(){return p_id;}
};


struct PeerComparator {
	bool operator()(const Peer* e1, const Peer* e2) {
		if (e1->id() - e2->id() != 0) 
		  return e1->id() > e2->id();	
		
	}
};

int main(int argc, char*argv[])
{
  set<Peer*,PeerComparator> ps;
  for(int i=0;i<5;i++)
      {Peer* pp=new Peer(i);
        ps.insert(pp);
        }
  
  for(set<Peer*, PeerComparator>::iterator it=ps.begin();it!=ps.end();it++)
    cout<<(*it)->id()<<endl;          
}    


error: passing ‘const Peer’ as ‘this’ argument of ‘int Peer::id()’ discards qualifiers
Last edited on
In a std::set, the value is also the key. In order to maintain its internal sorting, the key must be constant.

In other words, it's using set<const Peer *, PeerComparator>.

The error message says that in order to be const-correct, Peer::id() should be a const method (because symantically, it does not modify the state of the object).

You may need to use a const_iterator, too.
Topic archived. No new replies allowed.