首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在priority_queue中存储3个整数?

如何在priority_queue中存储3个整数?
EN

Stack Overflow用户
提问于 2011-04-19 13:56:21
回答 3查看 9.2K关注 0票数 6

我想在priority_queue中存储3个整数。我知道如何存储2个整数。我用pair<int,int>存储2个整数

我的代码

代码语言:javascript
复制
priority_queue<pair<int,int> , vector<pair<int,int> > , greater<pair<int,int> > > pq;
pq.push(make_pair(5,6));

但我不知道如何存储3个整数。我需要帮助。

对不起,我的英语不好。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-04-19 14:05:14

最简单的方法是创建一个struct,它在逻辑上绑定所有整数,并创建一个结构对象的优先级队列。

编辑示例代码:

代码语言:javascript
复制
#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;
}
票数 8
EN

Stack Overflow用户

发布于 2011-04-19 14:25:29

或者更简单的方式:std::pair<int,std::pair<int,int>>

票数 5
EN

Stack Overflow用户

发布于 2011-04-19 13:58:55

您可以使用Boost::Tuple

代码语言:javascript
复制
#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;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5712172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档