一个反向适配器的的例子

    技术2024-12-21  4

    #include<iostream> using namespace std; //反向适配器类 template<typename ReversedIterator, typename MutualIterator > class CReversed { public: //friend bool operator ==(const CReversed &it1, const CReversed &it2); //friend bool operator !=(const CReversed &it1, const CReversed &it2); public: CReversed():m_it(NULL){} explicit CReversed(MutualIterator i):m_it(i){} operator MutualIterator(){return m_it;} ~CReversed(){} public: //获取原双向迭代器中的最后一个元素,也就是逾尾的前一个元素 ReversedIterator &operator *() { MutualIterator i = m_it; --i; return *i; } public: //类中的数据成员保存的是,传递进来的迭代器的末尾的下一个元素, //自加表示从后往前迭代 CReversed &operator ++(){ --m_it; return *this;} CReversed &operator ++(int) { MutualIterator rTemp = *this; --m_it; return rTemp; } CReversed &operator --() { ++m_it; return *this;} CReversed &operator --(int) { MutualIterator rTemp = *this; ++m_it; return rTemp; } public: MutualIterator m_it; }; /*template<typename ReversedIterator, typename MutualIterator> bool operator == (const CReversed<ReversedIterator,MutualIterator> &it1, const CReversed<ReversedIterator,MutualIterator> &it2) { return it1.m_it == it2.m_it; } */ /*template<typename ReversedIterator, typename MutualIterator> bool operator != (const CReversed<ReversedIterator,MutualIterator> &it1, const CReversed<ReversedIterator,MutualIterator> &it2) { return it1.m_it != it2.m_it; } */ template<typename PTR, typename DATA> PTR Find(PTR Start, PTR Beyond, DATA data) { PTR Begin = Start; PTR End = Beyond; while(Begin != End && *Begin != data) ++Begin; return Begin; } int main() { int a[] = {1,2,3,4,5}; int *p = Find(a,a+5,3); typedef CReversed<int ,int*> R; R r = Find(R(a+5),R(a),3); cout<<r<<endl; cout<<p<<endl; }

    最新回复(0)