如何使用STL PriorityQueue 優先隊列

來源:互聯網
上載者:User

相信大家對優先隊列不陌生。

STL提供的PriorityQueue屬於容器適配器,底層預設用vector容器來實現。實現原理是在用vector裡構造一個

Heap(堆),堆一般是用數組來儲存的。

下面是一個使用有限隊列的例子,用來實現一個錯誤關聯器,總是把優先順序高的錯誤放在最前面。

#include <string>

#include <queue>

#include <ostream>

#include <stdexcept>

// this class is implemented as inline.

// since it is just very simple

class Error

{

public:

Error(const std::string& e, int p) : errormessage(e), priority(p) {}

std::string GetErrorMessage() const { return errormessage;}

int GetPriority() const { return priority;}

void SetErrorMessage(const std::string& s) { errormessage = s;}

void SetPriority(int p) { priority = p; }

friend bool operator<(const Error& lhs, const Error& rhs); 

friend std::ostream& operator<<(std::ostream& out, const Error& e);

private:

std::string errormessage;

int priority;

};

 

class ErrorCorrector

{

public:

ErrorCorrector() {};

// add an error to the queue

void AddError(const Error& e);

// get error

Error GetError();

bool IsEmpty() const { return mErrors.empty();}

private:

std::priority_queue<Error>  mErrors;

ErrorCorrector(const ErrorCorrector&);

ErrorCorrector& operator=(const ErrorCorrector&);

};

 

實現:

#include "PriorityError.h"

std::ostream& operator<<(std::ostream& out, const Error& e )

{

out << e.priority << ": " << e.errormessage << std::endl;

return out;

}

void ErrorCorrector::AddError( const Error& e )

{

   mErrors.push(e);

}

Error ErrorCorrector::GetError()

{

  if (mErrors.empty())

  {

    throw std::out_of_range("the error is not empty");

  }

 

  Error e = mErrors.top();

  mErrors.pop();

  return  e;

}

bool operator<( const Error& lhs, const Error& rhs )

{

  return lhs.priority < rhs.priority;

}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.