修改前
#include<iostream> #include<list> #include<algorithm> #include<iterator> using namespace std; struct node{ int key; int value; bool operator==(node *&p){ return p->value==value; } }; int main(){ list<node*>p; node *a1=new node; a1->key=1; a1->value=1; node *a2=new node; a2->key=1; a2->value=2; node *a3=new node; a3->key=1; a3->value=3; node *a4=new node; a4->key=1; a4->value=1; p.push_back(a1); p.push_back(a2); p.push_back(a3); list<node*>::iterator it; int ncount=count(p.begin(),p.end(),a4); cout<<ncount; list<node*>::iterator it; it=find(p.begin(),p.end(),a4); if(it!=p.end()) cout<<"find"; }
修改後:#include<iostream> #include<list> #include<algorithm> #include<iterator> using namespace std; struct node { int key; int value; //无用,删除 // bool operator==(node *&p) // { // return p->value==value; // } }; //添加指针比较函数 struct NodeCompare { node* n; NodeCompare(node* n1) { n = n1; } bool operator()(const node* n1) { return n1->value == n->value; } }; int main() { list<node*>p; node *a1=new node; a1->key=1; a1->value=1; node *a2=new node; a2->key=1; a2->value=2; node *a3=new node; a3->key=1; a3->value=3; node *a4=new node; a4->key=1; a4->value=1; p.push_back(a1); p.push_back(a2); p.push_back(a3); //重定义,删除 // list<node*>::iterator it; //指针时使用count_if // int ncount=count(p.begin(),p.end(),a4); NodeCompare comp(a4); int ncount = count_if(p.begin(), p.end(), comp); cout<<ncount; list<node*>::iterator it; //同理,此处也改为find_if // it=find(p.begin(),p.end(),a4); it = find_if(p.begin(), p.end(), comp); if(it!=p.end()) cout<<"find"; //添加容器内存释放 for (it=p.begin(); it!=p.end(); ++it) { delete *it; } //添加程序返回值 return 0; }
#include<iostream> #include<list> #include<algorithm> #include<iterator> using namespace std; struct node { int key; int value; }; struct nodeptr{ node* p; nodeptr(node* p):p(p){} bool operator == (const nodeptr &p2)const{ return p->value == p2.p->value; } bool operator != (const nodeptr &p2)const{ return p->value != p2.p->value; } }; int main() { list<nodeptr> p; node *a1=new node; a1->key=1; a1->value=1; node *a2=new node; a2->key=1; a2->value=2; node *a3=new node; a3->key=1; a3->value=3; node *a4=new node; a4->key=1; a4->value=1; p.push_back(nodeptr(a1)); p.push_back(nodeptr(a2)); p.push_back(nodeptr(a3)); list<nodeptr>::iterator it; int ncount=count(p.begin(),p.end(),nodeptr(a4)); cout<<ncount<<endl; it=find(p.begin(),p.end(), nodeptr(a4)); if(it!=p.end()) cout<<"find"<<endl; }
list<node*>::iterator it; int ncount=count(p.begin(),p.end(),a4); 你在list<node*>中的是指针,count函数也是找有没有相等的指针,并不是比较他指向的内容,应该: bool comp(node* a1,node*a2){ return a1->value == a2->value; } int ncount = count_if(p.begin(),p.end(),std::bind2nd(comp,a4));
请问这个ncount为什么是输出0呢,而且find那部分会出错
最新推荐文章于 2021-06-24 20:34:13 发布