0

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)). I don't understand how I can fix this issue.

9
  • 1
    You provide no way of comparing Vertex objects. Commented Mar 30, 2021 at 18:21
  • @sweenish but I don't compare any vertex objects? I only compare their memory addresses. Commented Mar 30, 2021 at 18:24
  • Why are you comparing adresses in your lambdas? Also why add the reference the pointers; you're not saving any space by using a reference to a pointer instead of a pointer. Commented Mar 30, 2021 at 18:25
  • @sweenish see the posted answer Commented Mar 30, 2021 at 18:25
  • 1
    @Jacob so I can check whether the two vectors have any pointers that point to the same vertex object -- Then that begs the question -- what do you do if you found out there are pointers pointing to the same vertex? In all honesty, your code looks like an XY problem scenario. Commented Mar 30, 2021 at 18:38

1 Answer 1

3

The parameters of your comparators are non-const references. More specifically, "references to non-const pointers to const Vertex".

You either need const references: const Vertex *const &one, or even better, just pass by value: const Vertex *one.

Also note that &*one < &*two is equivalent to one < two.

Sign up to request clarification or add additional context in comments.

2 Comments

@Jacob You're welcome! You can press the checkmark on the left to mark your question as solved.
I'm aware of this, but one can only do this after a certain amount of minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.