c++ - STL::sort() 中的比较函数

标签 c++ stl

class node{
public:
  unsigned long long int value;
  int index;
};


bool comp2(node& a,node& b){
  if(a.value < b.value) { return true; }
  return false;
}

vector <node*>llist,rlist;
sort(llist.begin(),llist.end(),comp2);

上面的代码给了我一些奇怪的错误,这在其他一些行中也有(放在代码的后面),但是当我将 comp2 函数更改为 following 时,所有错误都消失了。

bool comp2(node* a,node* b){
  assert(a && b && "comp2 - null argument");
  if(a->value < b->value){ return true; }
  return false;
}

有什么理由吗?

错误:/usr/include/c++/4.4/bits/STL_algo.h|124|错误:从类型为“node* const”的表达式中对类型为“node&”的引用的初始化无效|

如果这个(波纹管)有效,那么上面也应该有效

using namespace std;

void rep(int& a,int& b){

int c;
c=a;
a=b;
b=c;

}

int main(void){

int a=3,b=4;

rep(a,b);
cout<<a<<" "<<b;
return 0;
}

最佳答案

您已经定义了 node *std::vector。因此,所有的元素都是node *, vector 执行的所有操作都会在node *上进行。您不能为 sort 提供不同类型的比较函数。

关于c++ - STL::sort() 中的比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4701256/

相关文章:

c++ - 指针和容器

c++ - 从类访问主场景/层

c++ - 如何使用非平凡 (POD) 类的缓冲协议(protocol)实现 pybind11

C++ - 使用 std::string 的内容调用同名的类实例

c++ - 未捕获的 std::exception 在核心中不正确的堆栈跟踪

c++ - 可以插入 fstream,但不能插入 iostream

C++ undefined reference 类构造函数

c++ - 将 C++ 方法声明从 .hh 文件移动到 .cc 文件

C++ STL 设置 lower_bound 错误结果

c++ - 更改/添加 STL bitset<>::reference::operator=(int) 的行为