您的位置:首页 > 编程语言 > C语言/C++

C++ 高级编程 priority_queue 示例:错误关联器

2018-03-10 16:09 381 查看
参考 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: