對于STL容器而言,并不直接支援這一特性(也就是:list<myint&> mylist),
即便用raw pointer(也就是普通的指針list<myint*> mylist)也不能完全解決這個問題,
通常的解決方法是使用smart pointer來替代普通的指針進而完全控制:
construction,destruction,copying,assignment,以及dereference。
具體内容恐怕要參考侯sir的書了。
我試着寫了一個,僅供參考:
#include <list>
#include <iostream>
#include <functional>
//<string>
using namespace std;
struct myint
{
int key;
int data;
// bool operator < (const myint& _A){return (data < _A.data);};
// bool operator > (const myint& _A){return (data > _A.data);};
myint::myint():key(0),data(0){};
friend ostream& operator << (ostream&, const myint&);
friend bool operator > (const myint&, const myint&);
friend bool operator < (const myint&, const myint&);
};
ostream& operator << (ostream& _O, const myint& _C)
_O << _C.key<< " " << _C.data << ",";
return _O;
bool operator > (const myint& _A, const myint& _B)
return (_A.data > _B.data);
bool operator < (const myint& _A, const myint& _B)
return (_A.data < _B.data);
template <class T>
class MySmartPt
public:
T* ptr;
MySmartPt(T* p = 0): ptr(p){}
MySmartPt(const MySmartPt<T>& p) : ptr(p.ptr){}
~MySmartPt() {}
MySmartPt<T>& operator= (const MySmartPt<T>& p)
{
if(this != &p)
{
ptr = p.ptr;
}
return *this;
};
T& operator* () const {return *ptr;};
T& operator-> () const {return ptr;};
class MyintPt : public MySmartPt<myint>
MyintPt(myint* p) : MySmartPt<myint>(p){}
bool operator < (const MyintPt& rhs) const //
{return ( ((*this).ptr)->data < (rhs.ptr)->data);}
bool operator > (const MyintPt& rhs) const
{return ( ((*this).ptr)->data > (rhs.ptr)->data);}
int main()
myint array[10];
list<MyintPt> mylist;
myint temp;
for(int i = 0; i < 10; ++i )
temp.data = rand()%30;
array[i] = temp;
MyintPt myintPt(&array[i]);
mylist.push_back(myintPt);
cout << temp;
}
cout << endl;
typedef myint* pmyint;
mylist.sort();
list<MyintPt>::iterator iter;
for(iter = mylist.begin(); iter != mylist.end(); ++iter)
cout << *((*iter).ptr);
greater<MyintPt> pt;
mylist.sort(pt);
return 0;