📄 cache.hh
字号:
/* -*- c++ -*- --------------------------------------------------------------- Copyright (C) 2005, SWECO, All Rights Reserved. A simple priority cache. $Id$ Author: Zsolt Molnar (Zsolt.Molnar@ieee.org) ---------------------------------------------------------------------------*/#ifndef __CACHE_HH__#define __CACHE_HH__#include <vector>#include <algorithm>#include "base.hh"/*! \class Cache * \brief A simple cache for storing objects temporarily. * * Cache is a list which deletes the elements at its end if more items are added * than its maximal size. Accessing an element moves it to the beginning * of the list so always the "oldest" element is deleted. * Maximal size can be adjusted in run-time; oldest elements are deleted if * necessary. */template< class ELEM_TYPE >class Cache : public vector< ELEM_TYPE* >{public: // Interface // Construct/destruct/copy Cache ( const size_t aMaxSize ); virtual ~Cache (); // Methods virtual void setMaxSize ( const size_t aMaxSize ); size_t maxSize () const; ELEM_TYPE& accessElem ( const ELEM_TYPE& aElem );private: // Types typedef std::vector<ELEM_TYPE*> m_tType; protected: // Members size_t iMaxSize;};template< class ELEM_TYPE > inline Cache< ELEM_TYPE >::Cache( const size_t aMaxSize ) : iMaxSize( aMaxSize ){ // EMPTY}template< class ELEM_TYPE > inlineCache< ELEM_TYPE >::~Cache(){ Delete_All_Objects( *this );}template< class ELEM_TYPE > voidCache< ELEM_TYPE >::setMaxSize( const size_t aMaxSize ){ // Delete oldest elements if the number of elements more than the new maximal // size. if( aMaxSize < m_tType::size() ) { std::for_each( m_tType::begin() + aMaxSize, m_tType::end(), Delete_Object_t< ELEM_TYPE* >() ); erase( m_tType::begin() + aMaxSize, m_tType::end() ); } // Set new maximal size. iMaxSize = aMaxSize;}template< class ELEM_TYPE > inline size_t Cache< ELEM_TYPE >::maxSize() const{ return iMaxSize;}template< class ELEM_TYPE > ELEM_TYPE&Cache< ELEM_TYPE >::accessElem( const ELEM_TYPE& aElem ){ // Move aElem to the beginning of the list typename m_tType::iterator itr; for (itr = m_tType::begin(); itr != m_tType::end() && **itr != aElem; ++itr); ELEM_TYPE* elemPos; if (itr != m_tType::end()) { elemPos = *itr; erase(itr); } else { elemPos = new ELEM_TYPE(aElem); } insert(m_tType::begin(), elemPos); // Delete the oldest element if ran out of the list setMaxSize( iMaxSize ); return *elemPos;}#endif // #ifndef __CACHE_HH__
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -