【发布时间】:2015-02-06 10:18:37
【问题描述】:
我检查了 std::sort 和 std::priority_queue 的原型,模板中定义的自定义比较类型看起来非常相似。
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
template <class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
但实际上它们不同,std::sort 接受函数谓词,而 std::priority_queue 接受 struct(a type)。 为什么?提前致谢!
struct cmp {
bool operator() (const int &a, const int &b) {
return a < b;
}
};
vector<int> v;
v.push_back(2);
v.push_back(3);
v.push_back(1);
// this works
sort(v.begin(), v.end(), [](const int &a, const int &b) -> bool {
return a < b;
});
// this not works
// sort(v.begin(), v.end(), cmp);
cout << v[0] << endl;
// this works
priority_queue<int, cmp> q;
// this not works
// priority_queue<int, [](const int &a, const int &b) -> bool {
// return a < b;
// }> q;
q.push(2);
q.push(3);
q.push(1);
cout << q.top() << endl;
【问题讨论】:
标签: c++ c++11 stl comparator