Home > Mobile >  Create comparator for inserting triplets in min priority queue
Create comparator for inserting triplets in min priority queue

Time:12-18

I have made a triplet using a class with all members as integers. I want to insert the triplet in min priority queue using STL in C . I heard that it can be done using a bool comparator function, but don't have any idea about how to use it with 3 elements.

Note: I don't want to use vector pairs for inserting 3 values (I know how to do it ), I only want to use class triplets. Can someone help me in implementing it?

using namespace std;

#include<bits/stdc  .h>

class triplet{
    public:
    int element;
    int arrIndex;
    int elementIndex;
};

    priority_queue<triplet, vector<triplet>, greater<triplet>> pq;

CodePudding user response:

I don`t know why you did std::vector, std::greater but.

#include <queue>
#include <vector>
class triplet {
public:
    int element;
    int arrIndex;
    int elementIndex;

    constexpr bool operator>(const triplet& r)
    {
        return element > r.element;
    }
};

int main()
{
    std::priority_queue<triplet, std::vector<triplet>, std::greater<>> queue;
    triplet a, b;
    a.element = 3;
    b.element = 5;
    queue.push(a);
    queue.push(b);
}

This is possible by define a triplet operator.

or

#include <queue>
#include <vector>
class triplet {
public:
    int element;
    int arrIndex;
    int elementIndex;
};

template <>
struct std::greater<triplet>
{
    bool operator()(const triplet& l, const triplet& r)
    {
        return l.element > r.element;
    }
};

int main()
{
    std::priority_queue<triplet, std::vector<triplet>, std::greater<triplet>> queue;
    triplet a, b;
    a.element = 3;
    b.element = 5;
    queue.push(a);
    queue.push(b);
}

through template specialization.

  •  Tags:  
  • c
  • Related