stl - comparison with a third variable in priority_queue, c++ -


on page: http://comsci.liu.edu/~jrodriguez/cs631sp08/c++priorityqueue.html author gives nice example of using priority queue in c++. in author shows how order various times serially. have similar problem in order times on basis of proximity given point in time. question how add third input comparer, parameter can considered. i.e. how can make t3 inside comparer variable passed outside.

#include <iostream> #include <queue> #include <iomanip> #include <cstdlib>  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)     {        time t3 = {{2,9,0}};         if (abs(t3.h - t2.h) > (t3.h - t1.h))          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}};      (int = 0; < 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; } 

thanks.

your comparator can parameterized @ instantiation:

class comparetime  {     time t; public:     comparetime(const time& arg) : t{arg} {}      bool operator()(const time& t1, const time& t2) const     {         return (abs(t.h - t2.h) > abs(t.h - t1.h));     } }; 

declared this:

    time mytime; // modify leisure...      // ...then create queue mytime fixed param     priority_queue<time, vector<time>, comparetime> pq{comparetime{mytime}; 

apologies in advance if syntax isn't spot-on. i'm without compiler @ moment, hope idea clear enough.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -