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

参考 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值