Reputation: 29724
I cannot sort the list which contains the pointers to objects of my 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, which 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);// as * &lhs doesn't work too
private:
Node<T> * left;
Node<T> * right;
T chosen_;
vector<T> data_;
bool isLeaf;
//...
};
outside the 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 then I want to sort before print, I 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> &)' : could not deduce template argument for 'const std::complex<_Other> &' from 'std::_List_iterator<_Mylist>'
with
[
_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 and settings\cf16r\moje dokumenty\visual studio 2010\projects\binomial_tree\binomial_tree\mybinomialtree.h(136) : see reference to 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
with
[
_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> *)
]
Upvotes: 1
Views: 888
Reputation: 7061
std::sort
requires random-access iterators, so it cannot be used with std::list
iterators.
http://msdn.microsoft.com/en-us/library/ecdecxh1(v=vs.100).aspx
Make sure you read the documentation for template functions carefully. Template errors can be a nightmare to deal with.
Edit:
As Christian mentioned, std::list
has its own sort method. You could just make these two 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);
Upvotes: 2