繁体   English   中英

c++ 对对象、向量进行排序的问题

[英]Problem with c++ sorting of objects, vectors

考虑以下代码:

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

当我尝试编译上述内容时,我收到错误: error: no matching function for call to object of type '(lambda at Graph.cpp:59:48)' if (__comp(*--__last, *__first)) 我不明白如何解决这个问题。

比较器的参数是非常量引用。 更具体地说,“对指向 const Vertex的非常量指针的引用”。

您要么需要 const 引用: const Vertex *const &one ,或者更好的是,只需按值传递: const Vertex *one

还要注意&*one < &*two等价于one < two

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM