jeudi 3 mai 2018

C++: A set object with user-defined predicate inside class definition

I guess this is a dumb question, but it doesn't hurt to ask it anyway.

I'm a C++ beginner and I'm trying to implement the Kruskal's Algorithm for finding the minimum spanning tree of a weighted (connected) undirected graph.

I began by creating a WeightedGraph class.

class WeightedGraph
{
private:
    int V;
    map<pair<int, int>, int> w_map;

public:
    // constructors and other member functions.
};

Initially I defined the private data member named w_map above for holding the weight of each edge. That is, if {u, v} is a graph edge, then w_map[{u, v}] gives a reference to this edge's weight.

One of the steps of the Kruskal's algorithm is the sorting of all the edges in the graph by nondecreasing order of their weights.

As far as I understand, a map is only sorted by key (either with the default < operator or the with a user-defined binary predicate). A map can't directly be sorted by mapped_value. Please, correct if I'm wrong here.

One option is to define and use, along with the w_map above, a set<pair<pair<int, int>, int> (let name it w_set), providing it our own predicate so that each element a from w_map is copied into w_set according to the value of a.second (its weight).

So if our predicate is this:

bool Comparer(const pair<pair<int, int>, int> &a, const pair<pair<int, int>, int> &b)
{
    return a.second < b.second;

}

then we can define w_set as follows:

set<pair<pair<int, int>, int>, decltype(Comparer)*> w_set(Comparer);

and use it in a member function for accessing the iterators of the private member w_map.

But

I was thinking, what if instead of

  • Using a map for storing edges and weight.
  • Defining a member function for only returning a set with the edges sorted by weight.

we use directly a set of the same type as w_set as a data member of WeightedGraph. In that case, at each element insertion the set will be sorted as expected.

So the thing I did was this:

class WeightedGraph
{
private:
    int V;
    set<pair<pair<int, int>, int>, decltype(SortByWeight)*> w_sorted(SortByWeight);

public:
    // constructors and other member functions.
};

But I'm getting the following error:

Unknown type name 'SortByWeight'

not recognizing SortByWeight that was passed as the comp parameter to the set constructor.

I honestly don't know what I'm doing wrong. I think I'm messing with something pretty obvious (with scopes maybe) but I can't figure out what.

Aucun commentaire:

Enregistrer un commentaire