所以这就是 Arch 的代码不能正常工作的原因,我认为最好将它展示给 OP。缺少的链接是从 std::list<> 中删除的相等性。 operator ==()
没有它就std::list<T>::remove()
无法比较发送的对象是否是正在检查删除的对象。
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
#include <queue>
#include <iomanip>
#include <ctime>
using namespace std;
// my rabbit (I don't have yours).
struct Rabbit
{
Rabbit(int weight=0, int size=0)
: weight(weight), size(size) {};
int weight;
int size;
// needed for std::list<>::remove()
bool operator ==(const Rabbit& other)
{
return weight == other.weight
&& size == other.size;
}
};
// write to output stream
std::ostream& operator <<(std::ostream& os, const Rabbit& rabbit)
{
os << '[' << setw(2) << rabbit.weight << ',' << setw(2) << rabbit.size << ']';
return os;
}
// functor for comparing two rabbits by address
struct CompareRabbitPtrs
{
bool operator ()(const Rabbit* left, const Rabbit* right)
{
return right->weight < left->weight ||
(right->weight == left->weight && right->size < left->size);
}
};
// some typedefs to make life a little easier. first the list
typedef std::list<Rabbit> RabbitList;
// now the priority_queue
typedef std::priority_queue<Rabbit*, std::vector<Rabbit*>, CompareRabbitPtrs> RabbitQueue;
int main()
{
// seed RNG
std::srand((unsigned)time(0));
RabbitList rabbits;
RabbitQueue rq;
// load up your rabbits.
for (int i=1;i<12;++i)
{
rabbits.push_back(Rabbit(std::rand() % 10 + 3,std::rand() % 20 + 5));
rq.push(&rabbits.back());
}
// show rabbits
std::copy(rabbits.begin(), rabbits.end(),
ostream_iterator<Rabbit>(cout,"\n"));
cout << endl;
// remove top N rabbits, in this case 2
for (int i=0;i<2;++i)
{
rabbits.remove(*rq.top());
rq.pop();
}
// show rabbits again.
std::copy(rabbits.begin(), rabbits.end(),
ostream_iterator<Rabbit>(cout,"\n"));
return 0;
}
样品运行输出
[11,17]
[ 6,17]
[ 8,11]
[12,14]
[ 7, 8]
[ 6,19]
[11,16]
[10,19]
[ 6,21]
[10,14]
[ 7,13]
[11,17]
[ 8,11]
[12,14]
[ 7, 8]
[11,16]
[10,19]
[ 6,21]
[10,14]
[ 7,13]