英文:
How do I pass a 'general' priority_queue as function argument in c++
问题
在我的main
函数中,我有一堆priority_queues
,它们都包含int
,但有些使用less<int>
,其他使用greater<int>
。
//std:: removed for clarity
priority_queue<int, vector<int>, less<int>> pq1;
priority_queue<int, vector<int>, greater<int>> pq2;
我希望创建一个函数,接受两个引用传递的priority_queue
,将第一个弹出并放入第二个。
但是,这给了我一个错误:
void f(priority_queue<int> &from, priority_queue<int> &to) {
int x = from.top();
from.pop();
to.push(x);
}
将我的priority_queues
传递给这个函数时,出现了错误(无法匹配函数调用)。
如何修复这个问题,而不需要为greater<int>
和less<int>
的组合创建四个单独的函数?
英文:
In my main
function, I have a bunch of priority_queues
all of them have int
in them, but some have less<int>
, others have greater<int>
:
//std:: removed for clarity
priority_queue<int, vector<int>, less<int>> pq1;
priority_queue<int, vector<int>, greater<int>> pq2;
I wish to make a function that accepts two priority_queue
by reference and pops the first and puts into the second.
But, this gives me an error:
void f(priority_queue<int> &from, priority_queue<int> &to) {
int x = from.top();
from.pop();
to.push(x);
}
When passing my priority_queues into the function, it gives me an error. (no matching function for call)
How can I fix this without making four separate functions for 'greater<int>' and 'less<int>' combinations?
答案1
得分: 4
只创建一个函数模板:
template<class C1, class L1, class C2, class L2>
void f(std::priority_queue<int, C1, L1> &from, std::priority_queue<int, C2, L2> &to) {
int x = from.top();
from.pop();
to.push(x);
}
英文:
Just create a function template:
template<class C1, class L1, class C2, class L2>
void f(std::priority_queue<int, C1, L1> &from, std::priority_queue<int, C2, L2> &to) {
int x = from.top();
from.pop();
to.push(x);
}
答案2
得分: 2
你可以按照 fabian 的答案 中描述的方式更改这个函数,但不要求提取的目标是另一个 priority_queue
,而是可以创建一个函数模板,简单地返回提取的值。
template<class C>
auto extract_top(C& c) {
struct popper {
~popper() {
c.pop();
}
C& c;
};
popper p{c};
return std::move(c.top());
}
然后,你可以将提取的值放入另一个 priority_queue
或者存储在任何你想要的地方:
pq2.emplace(extract_top(pq1));
英文:
You could change the function as described in fabian's answer but instead of requiring that the target of the extraction is another priority_queue
you could make it more generic by creating a function template that simply returns the extracted value.
template<class C>
auto extract_top(C& c) {
struct popper {
~popper() {
c.pop();
}
C& c;
};
popper p{c};
return std::move(c.top());
}
You could then put the extracted value in another priority_queue
or store it anywhere you'd like:
pq2.emplace(extract_top(pq1));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论