Below is the delete function for a hash table that uses separate-chaining.
This is working code and searches within the delete function.
void delete_elem(int value)
{
list<int> ::iterator itr;
int hashedIndex = hashFunction(value);
for (itr = myTable[hashedIndex].begin();
itr != myTable[hashedIndex].end(); itr++)
{
if (*itr == value)
{
break;
}
}
if (itr != myTable[hashedIndex].end())
{
myTable[hashedIndex].erase(itr);
}
else
{
cout << value << " was not found" << endl;
}
}
but this version doesn't work and uses a helper function to do the searching.
void delete_elem(int value)
{
// auxiliary iterator
list<int> ::iterator tmp;
if (search(value, tmp))
{
int hashedIndex = hashFunction(value);
cout << "here3" << endl;
myTable[hashedIndex].erase(tmp); // this line segfaults
cout << "here4" << endl;
}
else
{
cout << value << " was not found" << endl;
}
}
bool search(int value, list<int> ::iterator tmp)
{
int hashedIndex = hashFunction(value);
for (list<int> ::iterator itr = myTable[hashedIndex].begin();
itr != myTable[hashedIndex].end(); itr++)
{
if (*itr == value)
{
tmp = itr;
cout << "tmp: " << *tmp << "\n"; // outputs an int, which is fine
cout << "itr: " << *itr << "\n"; // outputs the same int, which is fine
break;
}
else
{
tmp = myTable[hashedIndex].end();
}
}
return tmp != myTable[hashedIndex].end();
}
Somehow the tmp in my delete_elem() wasn't affected by the search(). How can I change this?
UPDATE (fixed by passing the iterator to the search function as a reference, and just realizing that iterators are NOT pointers in C++, but use pointer-like syntax):
void delete_elem(int value)
{
list<int> ::iterator tmp;
if (search(value, &tmp)) // passed in tmp as an address
{
int hashedIndex = hashFunction(value);
cout << "here3" << endl;
myTable[hashedIndex].erase(tmp);
cout << "here4" << endl;
}
else
{
cout << value << " was not found" << endl;
}
}
bool search(int value, list<int> ::iterator *tmp)
{
int hashedIndex = hashFunction(value);
for (list<int> ::iterator itr = myTable[hashedIndex].begin();
itr != myTable[hashedIndex].end(); itr++)
{
if (*itr == value)
{
*tmp = itr; // edited
cout << "tmp: " << *(*tmp) << "\n"; // edited
cout << "itr: " << *itr << "\n"; // edited
break;
}
else
{
*tmp = myTable[hashedIndex].end(); // edited
}
}
return *tmp != myTable[hashedIndex].end(); // edited
}