【发布时间】:2015-03-11 11:25:58
【问题描述】:
我想创建自己的数据容器,例如STL-containers。
template <class priorityType = size_t, class Compare = std::less<priorityType>>
class task_queue
{
public:
task_queue(Compare c = Compare())
{
}
private:
std::priority_queue<priorityType, std::vector<priorityType>, Compare> tasks_id;
};
int main() {
struct foo
{
int a;
};
struct foo_compare
{
bool operator()(const foo& lhs, const foo& rhs) const {
return lhs.a < rhs.a;
}
};
task_queue<foo, foo_compare> queue{ foo_compare() };
}
我想在tasks_id PQ 中使用传递给构造函数的comparator。我该怎么做?
【问题讨论】:
-
如果你在构造函数中传递一个比较操作符,你将不会得到比较的编译时绑定,即你的代码效率会降低。
-
@ErikAlapää,但 STL 容器以这种方式使用这些东西。
-
一般来说,好的 C++ 代码,包括 STL,尽可能尝试使用编译时绑定。这就是为什么 C++ 中的 std::sort 比 C 快速排序快的原因之一。 (C++ 排序使用编译时限制比较,而普通 C 快速排序使用函数指针)。
-
_ -1:阅读
priority_queue文档的简单失败。 -
@LightnessRacesinOrbit,PQ 只是示例,并非实际应用。
标签: c++ c++11 stl containers comparator