C++ 高级编程 priority_queue 示例:错误关联器
2018-03-10 16:09
381 查看
参考 C++ 高级编程,实现 priority_queue 示例:错误关联器
error_correlation.h
test.cpp
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; }
相关文章推荐
- C++ 高级编程 queue 示例:一个网络数据包缓冲区
- 从零开始学C++之STL(十一):容器适配器(stack、 queue 、priority_queue)源码浅析与使用示例
- C++ 高级编程 vector 示例:循环调度类
- C++之STL(十一):容器适配器(stack、 queue 、priority_queue)源码浅析与使用示例
- UNIX环境高级编程中的apue.h错误
- 100个windows平台C++开发错误之编程
- C++的STL容器之容器适配器:stack、queue、priority_queue
- 【C++ STL应用与实现】13: 如何使用std::queue和std::priority_queue
- 谁都能看懂的C++ STL之优先队列(priority_queue)
- C/C++编程新手错误语录
- C++中堆的应用:make_heap, pop_heap, push_heap, sort_heap, priority_queue
- C++ STL priority_queue
- Boolan——C++开发工程师——C++面对对象高级编程(上)—— 第一周笔记
- [C/C++标准库]_[初级]_[优先队列priority_queue的使用]
- C++STL priority_queue 学习
- c++ 学习笔记(高级linux编程) day3
- C++之priority_queue
- priority_queue 用法与编程题目
- C++编程人员容易犯的10个C#错误——C++培训(三)
- C++ 高级编程 编写一个 STL 容器:基本 hashmap