[英]Problem with c++ sorting of objects, vectors
Consider the following code:考虑以下代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Vertex {
public:
int id;
vector<Vertex*> edges;
Vertex(int id) : id(id) {}
int get_id() const {return id;}
};
class Graph {
public:
vector<Vertex*> vertices;
Graph(int V) {
vertices.reserve(V);
}
void test(vector<Vertex*>& other) {
sort(vertices.begin(), vertices.end(), [](const Vertex*& one, const Vertex*& two) {return &*one < &*two;});
sort(other.begin(), other.end(), [](const Vertex*& one, const Vertex*& two) {return &*one < &*two;});
}
};
When I try to compile the above I get the error: error: no matching function for call to object of type '(lambda at Graph.cpp:59:48)' if (__comp(*--__last, *__first))
.当我尝试编译上述内容时,我收到错误:
error: no matching function for call to object of type '(lambda at Graph.cpp:59:48)' if (__comp(*--__last, *__first))
。 I don't understand how I can fix this issue.我不明白如何解决这个问题。
The parameters of your comparators are non-const references.比较器的参数是非常量引用。 More specifically, "references to non-const pointers to const
Vertex
".更具体地说,“对指向 const
Vertex
的非常量指针的引用”。
You either need const references: const Vertex *const &one
, or even better, just pass by value: const Vertex *one
.您要么需要 const 引用:
const Vertex *const &one
,或者更好的是,只需按值传递: const Vertex *one
。
Also note that &*one < &*two
is equivalent to one < two
.还要注意
&*one < &*two
等价于one < two
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.