c++ - list<myClass<int> * > sort -
i cannot sort list contains pointers objects of template class. template
class node{ public: node(void){} node(t choice, vector<t> & data); node(t choice, vector<t> & data, player p, int level, int pos, node<t> *pred, side); void addnodes(void); static list<node<t> * > nodes; friend class mybinomialtree<node<t>, t>; bool sorter(const node<t> * lhs, const node<t> * rhs);// * &lhs doesn't work private: node<t> * left; node<t> * right; t chosen_; vector<t> data_; bool isleaf; //... }; outside class:
template<class t> bool node<t>::sorter(const node<t> * lhs, const node<t> * rhs){ if((*lhs).level_==(*rhs).level_){ return (*lhs).pos_<(*rhs).pos_; }else{ return (*lhs).level_<(*rhs).level_; } } and want sort before print, have
template<class t> void node<t>::print(void){ std::sort(node<t>::nodes.begin(),node<t>::nodes.end(),&node<t>::sorter); cout<<endl<<"after sort:"<<endl; list<node<t> * >::iterator it=node<t>::nodes.begin();cout<<endl; while(it!=node<t>::nodes.end()){ //... } } errors:
c:\program files\microsoft visual studio 10.0\vc\include\algorithm(3806): error c2784: 'std::complex<_other> std::operator -(const _ty &,const std::complex<_other> &)' : not deduce template argument 'const std::complex<_other> &' 'std::_list_iterator<_mylist>' [ _mylist=std::_list_val<node<int> *,std::allocator<node<int> *>> ] c:\program files\microsoft visual studio 10.0\vc\include\xcomplex(52) : see declaration of 'std::operator -' c:\documents , settings\cf16r\moje dokumenty\visual studio 2010\projects\binomial_tree\binomial_tree\mybinomialtree.h(136) : see reference function template instantiation 'void std::sort<std::_list_iterator<_mylist>,bool(__thiscall node<t>::* )(const node<t> *,const node<t> *)>(_ranit,_ranit,_pr)' being compiled [ _mylist=std::_list_val<node<int> *,std::allocator<node<int> *>>, t=int, _ranit=std::_list_iterator<std::_list_val<node<int> *,std::allocator<node<int> *>>>, _pr=bool (__thiscall node<int>::* )(const node<int> *,const node<int> *) ]
std::sort requires random-access iterators, cannot used std::list iterators.
http://msdn.microsoft.com/en-us/library/ecdecxh1(v=vs.100).aspx
make sure read documentation template functions carefully. template errors can nightmare deal with.
edit:
as christian mentioned, std::list has own sort method. make these 2 changes:
bool sorter(const node<t> * lhs, const node<t> * rhs);
static bool sorter(const node<t> * lhs, const node<t> * rhs);
std::sort(node<t>::nodes.begin(),node<t>::nodes.end(),&node<t>::sorter);
nodes.sort(&node<t>::sorter);
Comments
Post a Comment