簡體   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