参考 C++ 高级编程,实现 priority_queue 示例:错误关联器
error_correlation.h
#include <ostream>
#include <string>
#include <queue>
#include <stdexcept>
using namespace std;
class Error
{
public:
Error(int priority, string errMsg)
: mPriority(priority), mError(errMsg)
{
}
int getPriority() const
{
return mPriority;
}
string getErrorString() const
{
return mError;
}
friend bool operator<(const Error& lhs, const Error& rhs);
friend ostream& operator<<(ostream& os, const Error& error);
private:
int mPriority;
string mError;
};
bool operator<(const Error& lhs, const Error& rhs)
{
return lhs.getPriority() < rhs.getPriority();
}
ostream& operator<<(ostream& os, const Error& error)
{
os << error.getErrorString() << "(priority " << error.getPriority() << ")" << endl;
return os;
}
class ErrorCorrelation
{
public:
ErrorCorrelation()
{
}
void addError(const Error& error);
Error getError() throw(std::out_of_range);
private:
ErrorCorrelation(const ErrorCorrelation& src);
ErrorCorrelation& operator=(const ErrorCorrelation& rhs);
priority_queue<Error> mErrors;
};
void ErrorCorrelation::addError(const Error& error)
{
mErrors.push(error);
}
Error ErrorCorrelation::getError() throw(std::out_of_range)
{
if (mErrors.empty())
{
throw std::out_of_range("no elements");
}
Error error = mErrors.top();
mErrors.pop();
return error;
}
test.cpp
#include "error_correlation.h"
#include <iostream>
using namespace std;
int main()
{
ErrorCorrelation ec;
ec.addError(Error(3, "unable to open file"));
ec.addError(Error(1, "invalid input from user"));
ec.addError(Error(10, "unable to allocate memory"));
while (true)
{
try
{
Error e = ec.getError();
cout << e << endl;
}
catch (std::out_of_range)
{
cout << "finished processing errors" << endl;
break;
}
}
return 0;
}