【发布时间】:2015-07-22 20:35:58
【问题描述】:
我正在学习如何在 C++ 中使用 STL。我正在尝试使用std::priority_queue 实现堆。这是我的尝试:
#include<vector>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
#include<functional>
using namespace std;
struct data {
int first;
int second;
};
class compare {
public:
bool operator()(data &a ,data &b)
{
if(a.first < b.first) return true;
else false;
}
};
int main()
{
priority_queue <data , vector<data>, compare> heap;
data temp2[] = { {5,19},{2,7},{90,9},{12,6} };
for(int i = 0; i < 4; ++i)
{
heap.push(temp2[i]);
}
while(heap.empty() == false)
{
cout << heap.top().first << endl;;
heap.pop();
}
}
当我在 Visual Studio 2012 上运行此代码时。它在推送第二个元素时崩溃。错误如下:
Program: C:\WINDOWS\system32\MSVCP110D.dll
File: c:\program files (x86)\microsoft visual studio 11.0\vc\include\algorithm
Line: 2463
Expression: invalid operator<
但是当我在 ideone 中运行相同的代码时,它可以工作,但输出错误。 Ideone link
1.谁能指出我哪里出错了?
在同一个问题中再添加一个问题:
2.如何写 this 的 lambda 表达式而不是使用 compare 函数?
【问题讨论】:
标签: c++ stl priority-queue