HashTable remove function

I am very new to C++ and I am working on creating a program using HashTables. This is for homework. This is the first time I am using and creating HashTables, so forgive me in advance as to I don't know entirely what I am doing. The main problem I am having right now is incorporating my remove() function. I can get the code to compile, but when I run test the program out, it crashes. The error that I am receiving is
list iterator is not decrementable
Here is my hashtable class as well as my remove() function. Also need to incorporate a print method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class HTable
{
public:
	HTable(int size);
	void insert(  const string &s);
	void remove(const string &key);
	void print() const;

	
private:
	vector<list<string>> List;
	int currSize;
	int tableSize;
	int hash(string key)const;
	int hashFunction(string key);
	int HTableSize;
	int *status_arr;
	ostream &   operator <<( ostream &);
	static int const TABLE_SIZE = 97;				//The hash table size
	HTable *hashTable[TABLE_SIZE];
	bool getKey(string searchKey) const;
};


here is my remove function
1
2
3
4
5
6
7
8
9
10
11
12
13
inline void HTable::remove( const string &key)
{
	vector<list<string> >::iterator it;
   for ( it = List.begin(); it != List.end(); it ++)
   {

     if( find( (*it).begin( ), (*it).end( ), key )  !=  (*it).end( ) )
     {
        (*it).pop_back();
     }
   }
    
}


updated remove function. now does not crash.

Last edited on
List is a local variable that is empty and it has no relation to the data member of the same name.

Trying to find something in an empty list is an exercise in futility.
But, I wonder how can this code crash ?
I suspect it isn't the source of the crash.
the code crashes when it calls the pop.back(). how would i traverse through my member list? i know i would have to go through the vector, then go through the List, and find if key is there, but i cannot seem to translate that into code.
updated remove function. now does not crash.

It also does not work correctly.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
inline void HTable::remove( const string &key)
{
    vector<list<string>>::iterator it = List.begin() ;

    bool found = false ;                                    // stop looking when the key is found.
    while ( !found && it != List.end() )
    {
        list<string>::iterator at ;                         // if the list isn't empty, search it.
        if ( !it->empty() && (at=find(it->begin(), it->end(), key)) != it->end())
        {
            it->erase(at) ;                                 // found it, now remove it.
            found = true ;
        }
        else
            ++it ;                                          // not found, check the next list.
    }
}


This will need some modification if multiple copies of the same key are allowed and remove should remove all of them.

Last edited on
Topic archived. No new replies allowed.