How can I create Min stl priority_queue? - c++

The default stl priority queue is a Max one (Top function returns the largest element).
Say, for simplicity, that it is a priority queue of int values.

Use std::greater as the comparison function:
std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;

One way would be to define a suitable comparator with which to operate on the ordinary priority queue, such that its priority gets reversed:
#include <iostream>
#include <queue>
using namespace std;
struct compare
{
bool operator()(const int& l, const int& r)
{
return l > r;
}
};
int main()
{
priority_queue<int,vector<int>, compare > pq;
pq.push(3);
pq.push(5);
pq.push(1);
pq.push(8);
while ( !pq.empty() )
{
cout << pq.top() << endl;
pq.pop();
}
cin.get();
}
Which would output 1, 3, 5, 8 respectively.
Some examples of using priority queues via STL and Sedgewick's implementations are given here.

The third template parameter for priority_queue is the comparator. Set it to use greater.
e.g.
std::priority_queue<int, std::vector<int>, std::greater<int> > max_queue;
You'll need #include <functional> for std::greater.

You can do it in multiple ways:
1. Using greater as comparison function :
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> >pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<< " ";
}
return 0;
}
2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :
int main()
{
priority_queue<int>pq2;
pq2.push(-1); //for +1
pq2.push(-2); //for +2
pq2.push(-3); //for +3
pq2.push(4); //for -4
while(!pq2.empty())
{
int r = pq2.top();
pq2.pop();
cout<<-r<<" ";
}
return 0;
}
3. Using custom structure or class :
struct compare
{
bool operator()(const int & a, const int & b)
{
return a>b;
}
};
int main()
{
priority_queue<int,vector<int>,compare> pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<<" ";
}
return 0;
}
4. Using custom structure or class you can use priority_queue in any order.
Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.
struct people
{
int age,salary;
};
struct compare{
bool operator()(const people & a, const people & b)
{
if(a.salary==b.salary)
{
return a.age>b.age;
}
else
{
return a.salary>b.salary;
}
}
};
int main()
{
priority_queue<people,vector<people>,compare> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
Same result can be obtained by operator overloading :
struct people
{
int age,salary;
bool operator< (const people & p)const
{
if(salary==p.salary)
{
return age>p.age;
}
else
{
return salary>p.salary;
}
}};
In main function :
priority_queue<people> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}

In C++11 you could also create an alias for convenience:
template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
And use it like this:
min_heap<int> my_heap;

One Way to solve this problem is, push the negative of each element in the priority_queue so the largest element will become the smallest element. At the time of making pop operation, take the negation of each element.
#include<bits/stdc++.h>
using namespace std;
int main(){
priority_queue<int> pq;
int i;
// push the negative of each element in priority_queue, so the largest number will become the smallest number
for (int i = 0; i < 5; i++)
{
cin>>j;
pq.push(j*-1);
}
for (int i = 0; i < 5; i++)
{
cout<<(-1)*pq.top()<<endl;
pq.pop();
}
}

Based on above all answers I created an example code for how to create priority queue. Note: It works C++11 and above compilers
#include <iostream>
#include <vector>
#include <iomanip>
#include <queue>
using namespace std;
// template for prirority Q
template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
template<class T> using max_heap = priority_queue<T, std::vector<T>>;
const int RANGE = 1000;
vector<int> get_sample_data(int size);
int main(){
int n;
cout << "Enter number of elements N = " ; cin >> n;
vector<int> dataset = get_sample_data(n);
max_heap<int> max_pq;
min_heap<int> min_pq;
// Push data to Priority Queue
for(int i: dataset){
max_pq.push(i);
min_pq.push(i);
}
while(!max_pq.empty() && !min_pq.empty()){
cout << setw(10) << min_pq.top()<< " | " << max_pq.top() << endl;
min_pq.pop();
max_pq.pop();
}
}
vector<int> get_sample_data(int size){
srand(time(NULL));
vector<int> dataset;
for(int i=0; i<size; i++){
dataset.push_back(rand()%RANGE);
}
return dataset;
}
Output of Above code
Enter number of elements N = 4
33 | 535
49 | 411
411 | 49
535 | 33

We can do this using several ways.
Using template comparator parameter
int main()
{
priority_queue<int, vector<int>, greater<int> > pq;
pq.push(40);
pq.push(320);
pq.push(42);
pq.push(65);
pq.push(12);
cout<<pq.top()<<endl;
return 0;
}
Using used defined compartor class
struct comp
{
bool operator () (int lhs, int rhs)
{
return lhs > rhs;
}
};
int main()
{
priority_queue<int, vector<int>, comp> pq;
pq.push(40);
pq.push(320);
pq.push(42);
pq.push(65);
pq.push(12);
cout<<pq.top()<<endl;
return 0;
}

Multiply values with -1 and use max heap to get the effect of min heap

Related

Find max value in a vector recursively in C++

i am trying to wirte a function to find a the max value in a vector recursively. To do that i want to test in the findMax function if it can return the last value in the list right. But at the end, when the list has just one element, it returns me the adress of variable and not the value. Why is it?
/// finding max value in a list recursively
template <typename T>
int findMax(std::vector<T> arrayVector)
{
if(arrayVector.size()==1)
{
return arrayVector[0];
}
int op1= arrayVector[0];
std::vector<T> newVector (arrayVector.cbegin() + 1, arrayVector.cend());
disPlay(newVector);
int op2= findMax(newVector);
}
/// print vector
template <typename T>
void disPlay(std::vector<T> vectorArray)
{
for (int i=0; i< vectorArray.size(); i++)
{
std::cout << vectorArray[i] << "\t";
}
std::cout << "\n";
}
main()
{
std::vector<int> arrayVector = {6, 8, 19, 20, 23, 41, 49, 53, 56};
std::cout << findMax(arrayVector) << endl;
return 0;
}
I ran you program and it triggered several warnings, the one that probably justifies the unwanted behaviour is the lack of return value in int findMax(std::vector<T> arrayVector).
template <typename T>
int findMax(std::vector<T> arrayVector)
{
if(arrayVector.size()==1)
{
return arrayVector[0];
}
int op1= arrayVector[0];
std::vector<T> newVector (arrayVector.cbegin() + 1, arrayVector.cend());
disPlay(newVector);
int op2= findMax(newVector);
return op2; //<-- added return
}
I corrected the problems in https://wandbox.org/permlink/Kts9qs7MooG4dEQL
It seems ok now.
Use compiler warnings, it can save you a lot of time an headaches.
Now, this solves the issues with your code, but I would advise the use of std::max_element to get max values in a C++ data structure.
Here is a test sample of a function to get the max value recursively in an unordered vector witch loses the last element in each iteration:
template <typename T>
void findMax(std::vector<T>& arrayVector)
{
if(arrayVector.size() == 0) //stop condition
return;
int max = *std::max_element(arrayVector.begin(), arrayVector.end());
std::cout << "Max value: "<< max << std::endl;
arrayVector.erase(arrayVector.end() - 1); //last element being deleted in every recursion
findMax(arrayVector);
}
Check it in https://wandbox.org/permlink/0oyGnXoQdwhl3kUJ
template<typename T>
T findMax(const std::vector<T> vec, size_t index=0){
if(index==vec.size()-1) return vec[vec.size()-1];
return ( vec[index] > findMax(vec,index+1))?vec[index]:findMax(vec,index+1) ;
}
Your code is convoluted:
it's not actually computing the max of the vector
not all paths return a value
you are copying std::vector objects around with no real purpose
STL has the advantage of abstracting iterators, which make your attempt rather trivial:
template<typename T, typename C>
T findMax(C begin, C end)
{
if (begin+1 == end)
return *begin;
else
return std::max(*begin, findMax<T,C>(begin+1, end));
}
Mind: the code is not checking for correctness of input.
Can't be a recursive solution without ol' std::accumulate:
#include <iostream>
#include <vector>
#include <numeric>
#include <limits>
int main(int argc, char *argv[])
{
std::vector<int> arrayVector = {6, 8, 19, 20, 23, 41, 49, 53, 56};
const int max = std::accumulate(
arrayVector.cbegin(),
arrayVector.cend(),
std::numeric_limits<int>::min(),
[](int x, int y) { return x > y ? x : y; }
);
std::cout << max << '\n';
return 0;
}
Earlier solution by Rietty to similar question and solutions in this thread follow vector from 0 to end. Next follows vector from end to 0 to simplify recursive function:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
template<typename T>
T findMax (vector<T> values, size_t end) {
if (0 == end) return values[0];
return max (findMax (values, end - 1), values[end]);
}
template<typename T>
T inline findMax (vector<T> values) {
return findMax (values, values.size() - 1);
}
int main () {
vector<int> values = { 6, 8, 19, 20, 23, 41, 49, 53, 56 };
cout << findMax (values) << endl;
return 0;
}
Simple code:
int find_max(int a[], int length){
if (length == 0) return a[length];
return std::max(a[length-1], find_max(a, length-1));
}
#include "iostream"
#include "vector"
using namespace std;
int maxre(vector<int> array);
int main()
{
vector<int> data = {210, 800, 2,150 ,19,600};
cout << maxre(data);
return 0;
}
int maxre(vector<int> array)
{
static int index = -1;
if (array.size() == index + 1)
{
return 0;
}
else
{
index++;
int current = array[index];
int back = maxre(array);
return current > back ? current : back;
}
return 0;
}

C++ List showing last 3 items from table

Hey i have a table of teams with the names and the points they have and i'm trying to figure out how to display the last 3 teams with the least amount of points in the table?
It displays all the teams and i want it to display only the last 3 in the table but don't know what way to go about it.
These are my Accessors
string GetName
int GetPoints
int lowest = 1000;
for (int i = 0; i < numTeams; i++)
{
if (league[i].GetPoints() < lowest)
{
lowest = league[i].GetPoints();
}
}
for (int i = 0; i < numTeams; i++)
{
if (league[i].GetPoints() == lowest)
{
cout << "\tThe lowest goals against is: " << league[i].GetName() << endl;
}
}
Actually, you don't need variable lowest, if you would sort the data before printing.
#include <algorithm>
// Sort using a Lambda expression.
std::sort(std::begin(league), std::end(league), [](const League &a, const League &b) {
return a.GetPoints() < b.GetPoints();
});
int last = 3;
for (int i = 0; i < last; i++)
{
cout << "\tThe lowest goals against is: " << league[i].GetName() << endl;
}
U could probably start by sorting your array
#include <algorithm>
std::array<int> foo;
std::sort(foo.begin(), foo.end());
and then Iterate From Your Last Element to your Last - 3. (U can use Reverse Iterators)
for (std::vector<int>::reverse_iterator it = v.rend() ; it != v.rend() + 3;
it++) {
//Do something
}
or by using auto
for (auto it = v.rend() ; it != v.rend() + 3; ++it) {
//Do something
}
In my example I've created test class(TestTeam) to implement several important methods for objects in your task.
I use std::sort method to sort container of objects, by default std::sort compares objects by less(<) operation, so I have overrided operator < for TestTeam object
bool operator < ( const TestTeam& r) const
{
return GetPoints() < r.GetPoints();
}
Also we could pass as third parameter another compare method or lambda method as shown in below answers:
std::sort(VecTeam.begin(), VecTeam.end(), [](const TestTeam& l, const TestTeam& r)
{
return l.GetPoints() < r.GetPoints();
});
And example when we use global method to compare:
bool CompareTestTeamLess(const TestTeam& l, const TestTeam& r)
{
return l.GetPoints() < r.GetPoints();
}
//...
// some code
//...
// In main() we use global method to sort
std::sort(VecTeam.begin(), VecTeam.end(), ::CompareTestTeamLess);
You can try my code with vector as container:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
// Test class for example
class TestTeam
{
public:
TestTeam(int16_t p, const std::string& name = "Empty name"):mPoints(p), mName(name)
{
};
int16_t GetPoints() const {return mPoints;}
const std::string& GetName() const {return mName;}
void SetName( const std::string& name ) {mName=name;}
bool operator < ( const TestTeam& r) const
{
return GetPoints() < r.GetPoints();
}
private:
int16_t mPoints;
std::string mName;
};
int main(int argc, const char * argv[])
{
const uint32_t COUNT_LOWEST_ELEMENTS_TO_FIND = 3;
// Fill container by test data with a help of non-explicit constructor to solve your task
std::vector<TestTeam> VecTeam {3,5,8,9,11,2,14,7};
// Here you can do others manipulations with team data ...
//Sort vector by GetPoints overloaded in less operator. After sort first three elements will be with lowest points in container
std::sort(VecTeam.begin(), VecTeam.end());
//Print results as points - name
std::for_each( VecTeam.begin(), VecTeam.begin() + COUNT_LOWEST_ELEMENTS_TO_FIND, [] (TestTeam el)
{
std::cout << el.GetPoints() << " - " << el.GetName() << std::endl;
} );
}
I made test class TestTeam only to implement test logic for your object.
If you try launch the program you can get next results:
2 - Empty name
3 - Empty name
5 - Empty name
Program ended with exit code: 0

Change or delete elements of vector

I have following problem. My vector contains pairs of pairs (see example below).
In the example below I will push_back vector with some "random" data.
What will be best solution to delete the vector element if any of their values will be equal i.e. 100 and update value if less than 100.
i.e.
typedef std::pair<int, int> MyMap;
typedef std::pair<MyMap, MyMap> MyPair;
MyMap pair1;
MyMap pair2;
In first example I want to update this pair because pair1.first is less than 100
pair1.first = 0;
pair1.second = 101;
pair2.first = 101;
pair2.second = 101;
In second example I want to delete this pair because pair2.first is equal to 100
pair1.first = 0;
pair1.second = 101;
pair2.first = 100;
pair2.second = 101;
Using functor "check" I am able to delete one or more elements (in this example just one).
It is possible to increase every value of that pair by 1 using std::replace_if function?
Is there any function that will update this value if any of these values will be lower then "X" and delete if any of these values will be equal "X"?
I know how to do it writing my own function but I am curious.
#include "stdafx.h"
#include<algorithm>
#include<vector>
#include<iostream>
typedef std::pair<int, int> MyMap;
typedef std::pair<MyMap, MyMap> MyPair;
void PrintAll(std::vector<MyPair> & v);
void FillVectorWithSomeStuff(std::vector<MyPair> & v, int size);
class check
{
public:
check(int c)
: cmpValue(c)
{
}
bool operator()(const MyPair & mp) const
{
return (mp.first.first == cmpValue);
}
private:
int cmpValue;
};
int _tmain(int argc, _TCHAR* argv[])
{
const int size = 10;
std::vector<MyPair> vecotorOfMaps;
FillVectorWithSomeStuff(vecotorOfMaps, size);
PrintAll(vecotorOfMaps);
std::vector<MyPair>::iterator it = std::find_if(vecotorOfMaps.begin(), vecotorOfMaps.end(), check(0));
if (it != vecotorOfMaps.end()) vecotorOfMaps.erase(it);
PrintAll(vecotorOfMaps);
system("pause");
return 0;
}
std::ostream & operator<<(std::ostream & stream, const MyPair & mp)
{
stream << "First:First = " << mp.first.first << " First.Second = " << mp.first.second << std::endl;
stream << "Second:First = " << mp.second.first << " Second.Second = " << mp.second.second << std::endl;
stream << std::endl;
return stream;
}
void PrintAll(std::vector<MyPair> & v)
{
for (std::vector<MyPair>::iterator it = v.begin(); it != v.end(); ++it)
{
std::cout << *it;
}
}
void FillVectorWithSomeStuff(std::vector<MyPair> & v, int size)
{
for (int i = 0; i < size; ++i)
{
MyMap m1(i + i * 10, i + i * 20);
MyMap m2(i + i * 30, i + i * 40);
MyPair mp(m1, m2);
v.push_back(mp);
}
}
Use std::stable_partition, along with std::for_each:
#include <algorithm>
//...partition the elements in the vector
std::vector<MyPair>::iterator it =
std::stable_partition(vecotorOfMaps.begin(), vecotorOfMaps.end(), check(0));
//erase the ones equal to "check"
vecotorOfMaps.erase(vecotorOfMaps.begin(), it);
// adjust the ones that were left over
for_each(vecotorOfMaps.begin(), vecotorOfMaps.end(), add(1));
Basically, the stable_partition places all the items you will delete in the front of the array (the left side of the partiton it), and all of the other items to the right of it.
Then all that is done is to erase the items on the left of it (since they're equal to 100), and once that's done, go through the resulting vector, adding 1 to eac

How to use the priority queue STL for objects?

class Person
{
public:
int age;
};
I want to store objects of the class Person in a priority queue.
priority_queue< Person, vector<Person>, ??? >
I think I need to define a class for the comparison thing, but I am not sure about it.
Also, when we write,
priority_queue< int, vector<int>, greater<int> >
How does the greater work?
You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement
bool operator<(const Person& lhs, const Person& rhs);
it should work without any further changes. The implementation could be
bool operator<(const Person& lhs, const Person& rhs)
{
return lhs.age < rhs.age;
}
If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,
struct LessThanByAge
{
bool operator()(const Person& lhs, const Person& rhs) const
{
return lhs.age < rhs.age;
}
};
then instantiate the queue like this:
std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;
Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.
You would write a comparator class, for example:
struct CompareAge {
bool operator()(Person const & p1, Person const & p2) {
// return "true" if "p1" is ordered before "p2", for example:
return p1.age < p2.age;
}
};
and use that as the comparator argument:
priority_queue<Person, vector<Person>, CompareAge>
Using greater gives the opposite ordering to the default less, meaning that the queue will give you the lowest value rather than the highest.
A priority queue is an abstract data type that captures the idea of a container whose elements have "priorities" attached to them. An element of highest priority always appears at the front of the queue. If that element is removed, the next highest priority element advances to the front.
The C++ standard library defines a class template priority_queue, with the following operations:
push: Insert an element into the prioity queue.
top: Return (without removing it) a highest priority element from the priority queue.
pop: Remove a highest priority element from the priority queue.
size: Return the number of elements in the priority queue.
empty: Return true or false according to whether the priority queue is empty or not.
The following code snippet shows how to construct two priority queues, one that can contain integers and another one that can contain character strings:
#include <queue>
priority_queue<int> q1;
priority_queue<string> q2;
The following is an example of priority queue usage:
#include <string>
#include <queue>
#include <iostream>
using namespace std; // This is to make available the names of things defined in the standard library.
int main()
{
piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.
pq.push("the quick");
pq.push("fox");
pq.push("jumped over");
pq.push("the lazy dog");
// The strings are ordered inside the priority queue in lexicographic (dictionary) order:
// "fox", "jumped over", "the lazy dog", "the quick"
// The lowest priority string is "fox", and the highest priority string is "the quick"
while (!pq.empty()) {
cout << pq.top() << endl; // Print highest priority string
pq.pop(); // Remmove highest priority string
}
return 0;
}
The output of this program is:
the quick
the lazy dog
jumped over
fox
Since a queue follows a priority discipline, the strings are printed from highest to lowest priority.
Sometimes one needs to create a priority queue to contain user defined objects. In this case, the priority queue needs to know the comparison criterion used to determine which objects have the highest priority. This is done by means of a function object belonging to a class that overloads the operator (). The overloaded () acts as < for the purpose of determining priorities. For example, suppose we want to create a priority queue to store Time objects. A Time object has three fields: hours, minutes, seconds:
struct Time {
int h;
int m;
int s;
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
}
A priority queue to store times according the the above comparison criterion would be defined as follows:
priority_queue<Time, vector<Time>, CompareTime> pq;
Here is a complete program:
#include <iostream>
#include <queue>
#include <iomanip>
using namespace std;
struct Time {
int h; // >= 0
int m; // 0-59
int s; // 0-59
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2)
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
};
int main()
{
priority_queue<Time, vector<Time>, CompareTime> pq;
// Array of 4 time objects:
Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};
for (int i = 0; i < 4; ++i)
pq.push(t[i]);
while (! pq.empty()) {
Time t2 = pq.top();
cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
setw(3) << t2.s << endl;
pq.pop();
}
return 0;
}
The program prints the times from latest to earliest:
5 16 13
5 14 20
3 2 40
3 2 26
If we wanted earliest times to have the highest priority, we would redefine CompareTime like this:
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
{
if (t2.h < t1.h) return true;
if (t2.h == t1.h && t2.m < t1.m) return true;
if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
return false;
}
};
This piece of code may help..
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int age;
string name;
node(int a, string b){
age = a;
name = b;
}
};
bool operator<(const node& a, const node& b) {
node temp1=a,temp2=b;
if(a.age != b.age)
return a.age > b.age;
else{
return temp1.name.append(temp2.name) > temp2.name.append(temp1.name);
}
}
int main(){
priority_queue<node> pq;
node b(23,"prashantandsoon..");
node a(22,"prashant");
node c(22,"prashantonly");
pq.push(b);
pq.push(a);
pq.push(c);
int size = pq.size();
for (int i = 0; i < size; ++i)
{
cout<<pq.top().age<<" "<<pq.top().name<<"\n";
pq.pop();
}
}
Output:
22 prashantonly
22 prashant
23 prashantandsoon..
We can define user defined comparator: .The code below can be helpful for you.
Code Snippet :
#include<bits/stdc++.h>
using namespace std;
struct man
{
string name;
int priority;
};
class comparator
{
public:
bool operator()(const man& a, const man& b)
{
return a.priority<b.priority;
}
};
int main()
{
man arr[5];
priority_queue<man, vector<man>, comparator> pq;
for(int i=0; i<3; i++)
{
cin>>arr[i].name>>arr[i].priority;
pq.push(arr[i]);
}
while (!pq.empty())
{
cout<<pq.top().name<<" "<<pq.top().priority;
pq.pop();
cout<<endl;
}
return 0;
}
input :
batman 2
goku 9
mario 4
Output
goku 9
mario 4
batman 2

how can I store 3 integer in priority_queue?

I want to store 3 integer in priority_queue. I know how to store 2 integer.
I store 2 integer with pair<int,int>
my code
priority_queue<pair<int,int> , vector<pair<int,int> > , greater<pair<int,int> > > pq;
pq.push(make_pair(5,6));
but I don't know how can I store 3 integer. I need help.
sorry for my English.
Simplest would be create a struct which logically binds all the integers and create a priority queue of that struct objects.
EDIT
Sample code:
#include <queue>
using namespace std;
struct S
{
int m_n1;
int m_n2;
int m_n3;
S(int n1, int n2, int n3) : m_n1(n1), m_n2(n2), m_n3(n3)
{
}
bool operator<(const struct S& other) const
{
//Your priority logic goes here
return m_n1 < other.m_n1;
}
};
int main()
{
priority_queue<S> pq;
//Add the elements to the queue
pq.push(S(1,2,3));
pq.push(S(4,2,3));
pq.push(S(2,2,3));
//This element will be S(4,2,3)
S s1 = pq.top();
pq.pop();
return 0;
}
or the easy way: std::pair<int,std::pair<int,int>>
You may use Boost::Tuple
#include "boost/tuple/tuple.hpp"
#include <queue>
#include <vector>
#include <iostream>
typedef boost::tuple<int, int, int> triple_t;
class my_greater {
public:
bool operator() (const triple_t& arg1, const triple_t& arg2) const
{
return arg1.get<0>() > arg2.get<0>();
return false;
}
};
typedef std::priority_queue<triple_t, std::vector<triple_t>, my_greater>
my_priority_queue;
int main()
{
my_priority_queue triples;
triples.push(boost::make_tuple(1,2,3));
triples.push(boost::make_tuple(10,20,30));
triples.push(boost::make_tuple(5,10,15));
triples.push(boost::make_tuple(15,30,45));
triples.push(boost::make_tuple(2,4,6));
std::cout << "Result: \n";
while (!triples.empty())
{
const triple_t& t = triples.top();
std::cout << t.get<0>() << ", " << t.get<1>() << ", " << t.get<2>() << std::endl;
triples.pop();
}
return 0;
}