data structures - C++ - run-time crashing of linear probing program -
i wrote program in c++ hashing using linear probing. code showing no error @ time of compilation when run it, computer shows notification program has stopped working. giving entire code below. please me out.
#include<iostream> #include<vector> using namespace std; class acc { public: int idata; double ddata; acc(int id,double dd) { idata = id; ddata = dd; } void displayacc() { cout<<"idata = "<<idata<<"\n"; cout<<"ddata = "<<ddata<<"\n"; } }; class linear_hash { private: vector<acc*> hasharray; int nelem; acc* noelem; public: linear_hash(int max) { nelem = max; hasharray.resize(nelem); noelem = new acc(-1,1.1); for(int = 0;i<max;i++) { hasharray[i] = null; } } int hashfunc(int key) { return key%nelem; } void insertacc(int id,double dd) { acc* newacc = new acc(id,dd); int hashval = hashfunc(id); while(hasharray[hashval]->idata!=-1&&hasharray[hashval]!=null) { hashval++; hashval = hashval%nelem; } hasharray[hashval] = newacc; } acc* search(int key) { int hashval = key%nelem; while(hasharray[hashval]->idata!=key&&hasharray[hashval]!=null) { hashval++; hashval = hashval%nelem; } if(hasharray[hashval]->idata==key) { return hasharray[hashval]; } else return null; } bool deleteacc(int key) { int hashval = hashfunc(key); while(hasharray[hashval]->idata!=key&&hasharray[hashval]!=null) { hashval++; hashval = hashval%nelem; } if(hasharray[hashval]==null) return false; else { acc* ptemp = hasharray[hashval]; hasharray[hashval] = noelem; delete ptemp; return true; } } }; int main(void) { int key; char val; linear_hash lh(20); lh.insertacc(100,100.1); lh.insertacc(204,204.204); lh.insertacc(105,105.10); lh.insertacc(237,348.23); lh.insertacc(209,923.23); lh.insertacc(230,230.23); lh.insertacc(403,348.34); lh.insertacc(405,938.50); lh.insertacc(450,348.23); lh.insertacc(945,495.409); while(val!='x') { cout<<"enter key searched\n"; cin>>key; if(lh.search(key)==null) cout<<key<<" not found\n"; else lh.search(key)->displayacc(); cout<<"enter key deleted\n"; cin>>key; if(lh.deleteacc(key)) cout<<key<<" has been deleted\n"; else cout<<"invalid request\n"; cout<<"do want continue\n"; cin>>val; } return 0; }
i unable use debugger in case don't know error is. have tried dry-running on paper wasn't able pin point bug.
near top of main this:
linear_hash lh(20); lh.insertacc(100,100.1);
the first line sets vector:
for(int = 0;i<max;i++) { hasharray[i] = null; }
so, before second line have vector of null
s. second line this:
acc* newacc = new acc(id,dd); int hashval = hashfunc(id); while(hasharray[hashval]->idata ...
so, hasharray contains nulls, try @ hasharray[hashval]->idata
i.e.
null->idata
you should check hasharray[hashval]!=null
before try it.
Comments
Post a Comment