预定义仿函数需要就地实例化(带空括号)以用于算法,但不能用作容器适配器(如 priority_queue)的类型参数。为什么不同?
#include <queue>
#include <vector>
#include <numeric>
int main(){
std::priority_queue<int, std::vector<int>,
// parentheses are NOT neded here: std::greater<>
std::greater<>> pq;
pq.push(1);
pq.push(2);
pq.push(3);
std::vector<int> v = {1, 2, 3};
auto result = accumulate(v.begin(), v.end(), 0,
// parentheses are needed here std::plus<>()
std::plus<>());
}
std::priority_queue
是一个带有类型模板参数的类模板。它的特化要求指定类型模板参数。 std::greater<>
是用作类型模板参数的类型。
另一方面,在算法中,您需要提供一个功能对象,例如
std::greater<>()
.