无法在C++中为指针向量创建自定义排序

gny*_*his 0 c++ sorting vector

我试图通过使用排序谓词为类指针向量创建自定义排序:

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

对于每个网络,我们按airtime()返回的float进行排序.

现在,我尝试使用如下:

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());
  }

}
Run Code Online (Sandbox Code Playgroud)

但是,我得到了很多这样的错误:

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
Run Code Online (Sandbox Code Playgroud)

我没有正确指定传递给谓词的参数吗?airtime()由继承Network类的类实现.

jac*_*ven 5

编译器警告你Network::airtime()忽略了和的const限定符.n1n2

解决方案是创建一个" const正确"的版本Network::airtime()(假设它实际上没有修改任何东西).

请参阅此答案以获取示例.