CHAPTER4-21.cpp
上传用户:fjc899
上传日期:2007-07-03
资源大小:187k
文件大小:2k
- //【实例4-21:利用指针技术对容器进行赋值操作实例】
- #include "stl.h"
- #include <iostream.h>
- using namespace std;
- // Let's say you want to put pointers to X into multiple STLcontainers.
- class X
- {
- public:
- X(int i) : i_(i) { ; }
- X(const X& x) : i_(x.i_) { }
- ~X() { }
- X& operator= (const X& x) { i_ = x.i_; }
- int operator()() const { return i_; }
- private:
- int i_;
- };
- bool operator== (const X& x1, const X& x2) { return x1() == x2(); }
- bool operator< (const X& x1, const X& x2) { return x1() < x2(); }
- // Define a simple wrapper class to put into STLcontainers. This one simple wraps X.
- class XPtrWrapper
- {
- public:
- XPtrWrapper(X* x = 0) : x_(x) { }
- XPtrWrapper(const XPtrWrapper& xw) : x_(xw.x_) { }
- ~XPtrWrapper() { }
- //XPtrWrapper& operator= (const XPtrWrapper& xw) { x_ = xw.x_; }
- const X* operator() () const { return x_; }
- X* operator() () { return x_; }
- private:
- X* x_;
- };
- bool operator== (const XPtrWrapper& xw1, const XPtrWrapper& xw2)
- { return (xw1.operator()() && xw2.operator()()) ? *xw1() == *xw2() : false; }
- bool operator< (const XPtrWrapper& xw1, const XPtrWrapper& xw2)
- { return (xw1() && xw2()) ? *xw1() < *xw2() : false; }
- void print(const XPtrWrapper& xw)
- { cout << " " << (*xw())(); }
- int main(int, char*[])
- { XPtrWrapper bucket[5];
- for(int i = 0; i < 5; ++i) { bucket[i] = XPtrWrapper(new X(i * i)); }
- random_shuffle(bucket, bucket + 5);
- list<XPtrWrapper> list1;
- copy(bucket, bucket + 5, back_insert_iterator<list<XPtrWrapper> > (list1));
- cout << "List of XPtrWrapper: (";
- for_each(list1.begin(), list1.end(), print);
- cout << ")" << endl;
- // now put these XPtrWrappers into a set. Note that I can use greater since I've defined operator> for it.
- set<XPtrWrapper, greater<XPtrWrapper> > set1;
- /* copy(list1.begin(), list1.end(),
- insert_iterator<set<XPtrWrapper, greater<XPtrWrapper> > >(set1, set1.begin()) );
- */
- cout << "Set of XPtrWrapper : [";
- for_each(set1.begin(), set1.end(), print);
- cout << "]" << endl;
- // now put these integers into a deque.
- deque<XPtrWrapper> deque1;
- copy(list1.begin(), list1.end(), back_insert_iterator<deque<XPtrWrapper> > (deque1) );
- cout << "Deque of XPtrWrapper : (";
- for_each(deque1.begin(), deque1.end(), print);
- cout << ")" << endl;
- return 0;
- }