How to add class objects into priority_queue in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <queue>

using std::cout;
using std::endl;
using std::priority_queue;
using std::string;

class Test {
	int priority;
	string language;
public:
	Test() {
		language = "";
		priority = 0;
	}
	Test(string l, int p) {
		language = l;
		priority = p;
	}

	string get_language() const {
		return language;
	}
	int get_priority() const {
		return priority;
	}
};

bool operator<(const Test &o1, const Test &o2)
{
	return o1.get_priority() < o2.get_priority();
}

int main()
{
	priority_queue<Test> pq;

	pq.push(Test("c", 9));
	pq.push(Test("java", 3));
	pq.push(Test("c++", 4));

	while (!pq.empty()) {
		cout << pq.top().get_language() << endl;
		pq.pop();
	}

	return 0;
}


/*
run:

c
c++
java

*/

 



answered Apr 23, 2018 by avibootz

Related questions

1 answer 135 views
1 answer 154 views
1 answer 189 views
1 answer 167 views
167 views asked Apr 23, 2018 by avibootz
1 answer 223 views
1 answer 211 views
...