stl priority_queue of C++ with struct
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15601973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
stl priority_queue of C++ with struct
提问by Manas Verma
How can we use STL priority_queue
for struct ?
Any illustrationof 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 ?
我们如何将 STLpriority_queue
用于 struct ?任何插图推及弹出,其中结构有多个数据类型的?
说:struct thing { int a; char b;} glass[10];
。
现在如何使用“int a”将这个结构放在 priority_queue 上进行排序?
回答by juanchopanza
Here is a slightly modified answer to your original question, which you deletedfor 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.
这是对您原始问题的略微修改的答案,您无缘无故地删除了该答案。原始文件包含足够的信息来让您弄清楚这一点,但它是这样的:提供使用int
for 比较的小于比较。
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;
}
};
then
然后
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();
回答by masoud
Overload <
operator for thing
:
重载<
运算符thing
:
struct thing
{
int a;
char b;
bool operator<(const thing &o) const
{
return a < o.a;
}
};
priority_queue<thing> pq;
thing t1, t2, t3;
// ...
pq.push(t1);
pq.push(t2);
// ...
t3 = pq.top();
pq.pop();
回答by Taohidul Islam
You need to implement a compare function or overload operator to tell priority queue that on which order you want to sort your custom data. When priority queue will sort your data then it will need a way to know how to compare among them. You have to specify this by passing a function to priority queue or overloading operator in you custom data class or structure.
您需要实现一个比较函数或重载运算符来告诉优先级队列您希望对自定义数据进行排序的顺序。当优先队列对您的数据进行排序时,它需要一种方法来了解如何在它们之间进行比较。您必须通过将函数传递给自定义数据类或结构中的优先级队列或重载运算符来指定这一点。
You can check thisanswer. Thismight help you. I have tried to explain multiple ways of using priority queue for custom data types.