gnychis
gnychis

Reputation: 7555

trouble creating a custom sort in C++ for a vector of pointers

I am trying to create a custom sort for a vector of class pointers by using a sort predicate:

struct sort_by_airtime                                                                                            
{                                                                                                                 
    inline bool operator() (const Network *n1, const Network *n2)                                                 
    {                                                                                                             
      return (n1->airtime() < n2->airtime());                                                                     
    }                                                                                                             
};      

For each network, we sort by a float returned by airtime().

Now, I try to use this as follows:

std::vector<Network *> Simulator::sort_networks(std::vector<Network *> netlist, bool sort_airtime) {

  std::vector<Network *> new_netlist = netlist;

  if(sort_airtime) {
    sort(new_netlist.begin(), new_netlist.end(), sort_by_airtime());
  }

}

However, I get a lot of errors like this:

In file included from Simulator.cpp:7:
Simulator.h: In member function ‘bool Simulator::sort_by_airtime::operator()(const Network*, const Network*)’:
Simulator.h:48: error: passing ‘const Network’ as ‘this’ argument of ‘virtual float Network::airtime()’ discards qualifiers
Simulator.h:48: error: passing ‘const Network’ as ‘this’ argument of ‘virtual float Network::airtime()’ discards qualifiers

Am I not specifying the argument passed to the predicate properly? airtime() is implemented by classes that inherit the Network class.

Upvotes: 0

Views: 355

Answers (3)

jacobhaven
jacobhaven

Reputation: 393

The compiler is warning you that Network::airtime() is ignoring the const qualifiers on n1 and n2.

The solution would be to create a "const-correct" version of Network::airtime() (assuming it actually doesn't modify anything).

See this answer for an example.

Upvotes: 5

Mike Seymour
Mike Seymour

Reputation: 254471

Network::airtime() is not const, and so can't be called via the const Network* you have in sort_by_airtime.

If possible, the best solution is to make airtime() const; otherwise change the sort_by_airtime arguments to Network*.

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

Your member function should be declared as const member function as:

virtual float Network::airtime() const 
                                 ^^^^^ //this makes the function const

because the pointers which you're using in operator() are pointing to const objects of type Network.

Upvotes: 3

Related Questions