本文介绍了stl priority_queue的C ++与struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何使用STL priority_queue for struct?
任何插图推送& popping,其中struct有多个数据类型?

说: struct thing {int a;

How can we use STL priority_queue for struct ?Any illustration of pushing & popping , where struct has multiple data-types?
Say : struct thing { int a; char b;} glass[10]; .
Now how can i put this struct on priority_queue using 'int a' for ordering ?

>

这里是对,没有明显的原因。原来包含足够的信息,你可以明白这一点,但在这里:提供比使用 int 比较的比较。

Here is a slightly modified answer to your original question, which you deleted for no apparent reason. The original contained enough information for you to figure this out, but here it goes: provide a less than comparison that uses the int for comparison.

所有你需要做的是提供一个实现比严格弱排序小于比较的函子,或者实现相同的类的小于运算符。此结构满足要求:

All you need to do is provide a functor that implements a less-than comparison with strict weak ordering, or a less-than operator for your class implementing the same. This struct satisfies the requirements:

struct thing
{
    int a;
    char b;
    bool operator<(const thing& rhs) const
    {
        return a < rhs.a;
    }
};

然后

std::priority_queue<thing> q;
thing stuff = {42, 'x'};
q.push(stuff);
q.push(thing{4242, 'y'}); // C++11 only
q.emplace(424242, 'z'); // C++11 only    
thing otherStuff = q.top();
q.pop();

这篇关于stl priority_queue的C ++与struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 18:30