hash table c++ strings - c++

Trying to Implement a hash table in C++, Where the table has to take in string data and must hold at least 10 items. Implemented this below but doesn't compile and have broke it somehow :(, open to other ideas on how is best to implement or a fix for this one
Thanks
Someone be a legend please. :)
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
class hash{
private:
static const int tableSize = 10;
struct item
{
string d;
item* next;
};
item* HashTable[tableSize];
public:
hash();//the constructor
int Hash(string key);
void AddItem(string d);//will add new item
int NumberOfItemsInBucket(int bucket);
void PrintTable();
void PrintItemsInBucket(int bucket);
};
hash::hash()
{
for(int i = 0;i < tableSize;i++)
{
HashTable[i] = new item;
HashTable[i]->d = "";
HashTable[i]->next = NULL;
}
};
void hash::AddItem(string d)
{
int bucket = Hash(d);
if(HashTable[bucket]->d == "")
{
HashTable[bucket]->d = d;
}
else
{
item* Ptr = HashTable[bucket];
item* n = new item;
n->d = d;
n->next = NULL;
while(Ptr->next != NULL)
{
Ptr = Ptr->next;
}
Ptr->next;
}
}
int hash::NumberOfItemsInBucket(int bucket)
{
int slot = 0;
if(HashTable[bucket]->d == "")
{
return slot;
}
else
{
slot++;
item* Ptr = HashTable[bucket];
while(Ptr->next != NULL)
{
slot++;
Ptr = Ptr->next;
}
}
return slot;
}
void hash::PrintTable()
{
int number;
for(int i = 0;i < tableSize;i++)
{
number = NumberOfItemsInBucket(i);
cout << "--------------------\n";
cout << "bucket = " << i << endl;
cout << "Data: " << HashTable[i]->d << endl;
cout << "No. of items = " << number << endl;
cout << "--------------------\n";
}
}
void hash::PrintItemsInBucket(int bucket){
item* Ptr = HashTable[bucket];
if(Ptr->d == ""){
cout << "bucket " << bucket << " is empty!\n";
}else{
cout << "Bucket " << bucket << " contains this: " << endl;
while(Ptr != NULL){
cout << "--------------------\n";
cout << Ptr->d << endl;
cout << "--------------------\n";
Ptr = Ptr->next;
}
}
}
int hash::Hash(string key){
int hash = 0;
int index;
for(int i = 0;i < key.length();i++)
{
hash = hash + (int)key[i];
//cout << "Hash = " << hash << endl; //displays the hash function result
}
index = hash % tableSize;
return index;
}
int main (){
hash newHash;
newHash.AddItem("restaurant");
newHash.AddItem("innovation");
newHash.AddItem("vegetarian");
newHash.AddItem("opposition");
newHash.AddItem("attractive");
newHash.AddItem("incredible");
newHash.AddItem("assessment");
newHash.AddItem("illustrate");
newHash.AddItem("presidency");
newHash.AddItem("background");
newHash.PrintTable();
//newHash.PrintItemsInBucket();
return 0;
}
Compile errors:
note: class hash
error: 'newHash' not declared in the scope
error: reference to 'hash' is ambiguous

Just remove the using manespace std; and add explicitly add std:: to endl, cout, and string.

Related

I m not getting correct output for pre and post order

// in this code I first created nodes stored them in a que and keep on removing them as I entered their left and right children. To make a node have no further children I entered -1 while entering data. Here I am not able to understand what is wrong with my code , I am getting wrong output for preorder and postorder traversals. It would be really great if you guys could help me out.
I made a class que for queue ds and inherited it in tree class in protected mode.
#include <iostream>
#include <math.h>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
class que
{
protected:
int start;
int end;
struct node **arr;
int n;
public:
que(int x)
{
n = x;
arr = new struct node *[n];
start = -1;
end = -1;
}
void isfull()
{
if (end == n)
cout << "Queue is full !!!" << endl;
return;
}
int isempty()
{
if (start == end)
{
start = -1;
end = -1;
cout << "Queue is empty !!!" << endl;
return 1;
}
return 0;
}
void enqu(struct node *x)
{
if (end == n)
{
cout << "called" << endl;
isfull();
return;
}
end++;
arr[end] = x;
}
struct node *dequ(void)
{
struct node *q = 0;
if (start == end)
{
isempty();
return q;
}
start++;
cout << "Element removed is ->" << arr[start] << endl;
return arr[start];
}
};
class tree : protected que
{
public:
struct node *head;
struct node *ptr;
tree(int n) : que(n)
{
head = 0;
ptr = 0;
enter();
}
void create(void)
{
ptr = new struct node;
ptr->left = 0;
ptr->right = 0;
}
void enter(void)
{
struct node *p;
if (head == 0)
{
create();
cout << "Enter root element of tree -> ";
cin >> ptr->data;
head = ptr;
cout << "Enquing ptr - " << ptr << endl;
enqu(ptr);
}
while (!isempty())
{
p = dequ();
cout << "Enter left child ->";
int x;
cin >> x;
if (x != -1)
{
create();
p->left = ptr;
ptr->data = x;
cout << "Enquing ptr - " << ptr << endl;
enqu(ptr);
}
cout << "Enter right child ->";
cin >> x;
if (x != -1)
{
create();
p->right = ptr;
ptr->data = x;
cout << "Enquing ptr - " << ptr << endl;
enqu(ptr);
}
}
}
void inorder(struct node *yes)
{
if (yes != 0)
{
inorder(yes->left);
cout << "--> " << yes->data << endl;
inorder(yes->right);
}
}
void preorder(struct node *yes)
{
if (yes != 0)
{
cout << "--> " << yes->data << endl;
inorder(yes->left);
inorder(yes->right);
}
}
void postorder(struct node *yes)
{
if (yes != 0)
{
inorder(yes->left);
inorder(yes->right);
cout << "--> " << yes->data << endl;
}
}
int count(struct node *yes)
{
static int x = 0, y = 0;
if (yes == 0)
return 0;
x = count(yes->left);
y = count(yes->right);
return x + y + 1;
}
int height(struct node *yes)
{
static int a = 0, b = 0;
if (yes == 0)
return 0;
a = count(yes->left);
b = count(yes->right);
if (a > b)
return a + 1;
else
return b + 1;
}
};
int main()
{
int x;
cout << "Enter height of tree - ";
cin >> x;
int max = 0;
max = pow(2, x + 1) - 1;
tree tr(max);
cout << "Preorder traversal -- " << endl;
tr.preorder(tr.head);
cout << "Inorder traversal -- " << endl;
tr.inorder(tr.head);
cout << "Postorder traversal -- " << endl;
tr.postorder(tr.head);
cout << "\n No. of elements -- " << tr.count(tr.head);
cout << "\n Height of tree --" << tr.height(tr.head);
}
The preorder and postorder functions doesn't call themselves recursively. Instead they call the inorder function, which will lead to all but the root will be printed using inorder.

Getting Misaligned access runtime error in c++ for a vector of pointers

Trie()
{
nxt.assign(26, NULL);
cout << nxt.size() << endl;
Trie* root = this;
isWord = false;
}
/** Inserts a word into the trie. */
void insert(string word)
{
auto node = root;
for (int i = 0; i < word.size(); i++)
{
cout << "node: " << node<< ":" << "word[i] -'a': " << word[i] - 'a' << endl;
if (node->nxt[word[i] - 'a'] == NULL ) // misaligned memory access here
node->nxt[word[i]-'a'] = new Trie();
node = node->nxt[word[i]-'a'];
}
node->isWord = true;
}
I am getting the following error although the vector seems to have correct length: Member access within misaligned address 0xbebebebebebebe for type 'Trie' which requires 8 byte alignment. Why is the nxt vector elements not accessible?
Update:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Trie {
public:
Trie() {
nxt.assign(26, NULL);
isWord = false;
}
void insert(string word) {
auto node = this;
for(int i = 0; i < word.size(); i++) {
if (!node->nxt[word[i]-'a']) {
cout << " nxt entry not found... :" << word[i] << endl;
node->nxt[word[i]-'a'] = new Trie();
}
else {
cout << "nxt entry found! :" << word[i] << endl;
node = node->nxt[word[i]-'a'];
}
node->isWord = true;
}
}
bool search(string word) {
auto node = this;
for(int i = 0; i < word.size(); i++) {
if (!node->nxt[word[i]-'a']) return false;
node = node->nxt[word[i]-'a'];
}
return node->isWord ? true: false;
}
private:
vector<Trie*> nxt;
bool isWord;
};
int main() {
Trie* trie = new Trie();
trie->insert("test");
cout << "found test: " << trie->search("test") << endl;
cout << "success!" << endl;
return 0;
}
This runs! Bailey's comment helped me realize my mistake. I had declared a local root in ctor. The intent was to only initialize the class member, root! Thank you!

C++ Depth First Search of Trie with prefix parameter

I'm trying to implement a trie that can print out the frequency of words with a given prefix.
Edit: Thanks to #kaidul-islam finding my error with the following error:
new_word->child[letter]->prefixes_++;
Below is the fixed code:
Trie Class:
class Trie
{
public:
Trie(): prefixes_(0), is_leaf_(false), frequency_(0)
{
for (int i=0; i<26; i++)
{
child[i] = nullptr;
}
}
virtual ~Trie();
//Child nodes of characters from a-z
Trie *child[26];
//vector<Trie> child;
int prefixes_;
//accessor & mutator functions
bool GetIsLeaf() { return is_leaf_; }
void SetIsLeaf(bool val) { is_leaf_ = val; }
int GetFrequency() { return frequency_; }
void SetFrequency(int val) { frequency_ = val; }
int GetPrefixes() { return prefixes_; }
void SetPrefixes(int val) { prefixes_ = val; }
bool is_leaf_;
private:
//bool is_leaf_;
int frequency_;
};
Function in Question:
void AddWord(string &word, Trie *root)
{
Trie *new_word = root;
new_word->prefixes_++;
for(unsigned int i = 0 ; i < word.length(); i++)
{
int letter = (int)word[i] - (int)'a'; //extract character of word
if(new_word->child[letter] == nullptr)
{
new_word->child[letter] = new Trie;
}
/*cout << "not value of x: " << new_word->child[letter]->GetPrefixes() << endl;
int x = (new_word->child[letter]->GetPrefixes())+1;
cout << "value of x: " << x << endl;
new_word->child[letter]->SetPrefixes(x);*/
new_word->child[letter]->prefixes_++;
new_word = new_word->child[letter];
}
new_word->SetFrequency(new_word->GetFrequency()+1);
/*
cout << "Word: " << word << endl;
cout << "frequency: " << new_word->GetFrequency() << endl;
cout << "prefixes: " << new_word->GetPrefixes() << endl;
cout << "is leaf: " << new_word->GetIsLeaf() << endl << endl;
*/
}
After a quick inspection, I found you didn't initialize member variables in your constructor.
Trie(): prefixes_(0),
is_leaf_(false),
frequency_(0) {
for(int i = 0; i < 26; i++) {
child[i] = nullptr;
}
}
Unlike global variable, there is no guarantee that prefixes_ will be 0 by default on declaration. And child[i] is not guaranteed to be nullptr too. You need to initialize everything.

Segmentation Fault (Core Dump) - Code works in VS but not in the Linux Terminal [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So, I can run this program in Visual Studio with absolutely no problems, producing correct output. However, after compiling in the Linux terminal, I get a seg fault when trying to run the same code. Upon debugging using GDB, the information given is not very helpful (will be provided below). The program consists of two header files and three .cpp files. I will provide all of them below, along with the debugging information given. (If the indenting is weird, it is because of the 4-space code indent rule for submission). I have been trying to find the issue for hours on end to no avail. I have a feeling it is a small, minor mistake. Thank you all very much in advance.
Song.h
#ifndef Song_h
#define Song_h
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <stdlib.h>
using namespace std;
class Song
{
private:
string artist;
string title;
int size;
public:
Song(); //declares blank song array
Song(string _title, string _artist, int _size); //initializes object with given parameters for Song instance
string getArtist() const
{
return artist;
}
string getTitle() const
{
return title;
}
int getSize() const
{
return size;
}
void setArtist(string _artist)
{
artist = _artist;
}
void setTitle(string _title)
{
title = _title;
}
void setSize(int _size)
{
size = _size;
}
bool operator == (Song const &rhs);
bool operator != (Song const &rhs);
bool operator > (Song const &rhs);
bool operator < (Song const &rhs);
};
#endif
TsuPod.h
#ifndef TsuPod_h
#define TsuPod_h
#include "Song.h"
//TsuPod class declaration
class TsuPod
{
private:
struct SongNode
{
Song data;
SongNode *next;
};
SongNode *songs; //the head pointer
static const int MAX_SIZE = 512;
static const int SUCCESS = 0;
static const int FAILURE = 1;
static const int NO_MEMORY = -1;
static const int NOT_FOUND = -2;
int getNumSongs();
int memSize;
public:
TsuPod();
TsuPod(int size);
~TsuPod();
int addSong(Song const &s);
int removeSong(Song const &s);
void shuffle();
void showSongList();
void sortSongList();
int getRemainingMemory();
int getTotalMemory()
{
return memSize;
}
};
Song.cpp
#endif
#include "TsuPod.h"
#include "Song.h"
Song::Song() //default constructor, initializes a blank song
{
artist = "";
title = "";
size = 0;
}
Song::Song(string _artist, string _title, int _size) //constructor for song when arguments are given by user
{
artist = _artist;
title = _title;
size = _size;
}
bool Song::operator == (Song const &rhs) //overloaded for sorting
{
return (title == rhs.title &&
artist == rhs.artist &&
size == rhs.size);
}
bool Song::operator != (Song const &rhs) //overloaded for sorting
{
return (title != rhs.title ||
artist != rhs.artist ||
size != rhs.size);
}
bool Song::operator > (Song const &rhs) //overloaded for sorting
{
if (artist != rhs.artist)
return (artist > rhs.artist);
else
if (title != rhs.title)
return (title > rhs.title);
else
if (size != rhs.size)
return (size > rhs.size);
else
return false;
}
bool Song::operator < (Song const &rhs) //overloaded for sorting
{
if (artist != rhs.artist)
return (artist < rhs.artist);
else
if (title != rhs.title)
return (title < rhs.title);
else
if (size != rhs.size)
return (size < rhs.size);
else
return false;
}
TsuPod.cpp
#include "TsuPod.h"
#include "Song.h"
TsuPod::TsuPod() //default constructor
{
memSize = MAX_SIZE;
}
TsuPod::TsuPod(int _size) //constructor for when user specifies their prefered memory size, prevents input of a size greater than MAX_SIZE or less than 0
{
if (_size > MAX_SIZE || _size <= 0)
memSize = MAX_SIZE;
else
memSize = _size;
}
TsuPod::~TsuPod() //destructor
{
SongNode *p;
while (songs != NULL)
{
p = songs;
songs = songs->next;
delete p;
}
}
int TsuPod::getRemainingMemory() //finds remaining memory, returns int value
{
int memSum = 0;
SongNode *p = songs;
while (p != NULL)
{
memSum += p->data.getSize();
p = p->next;
}
return memSize - memSum;
}
int TsuPod::addSong(Song const &s) //adds song to TsuPod, returns int number to display result, 0 = success, 1 = failure, -1 = not enough memory
{
if (s.getSize() > getRemainingMemory()) //ensures there is enough unsused memory for song
return NO_MEMORY;
if (s.getSize() > 0) //ensures song is valid
{
SongNode *temp = new SongNode;
temp->data = s;
temp->next = songs;
songs = temp;
return SUCCESS;
}
else
return FAILURE;
}
int TsuPod::removeSong(Song const &s) //removes song, returns int value to display result, 0 = success, 1 = failure, -2 = not found
{
if (songs != NULL)
{
SongNode *prev = NULL;
SongNode *p = songs;
if (p->data == s)
{
songs = p->next;
return SUCCESS;
}
while (p != NULL && p->data != s)
{
prev = p;
p = p->next;
if (songs->data == s)
{
songs = p->next;
delete p;
return SUCCESS;
}
else
if (p->data == s)
{
prev->next = p->next;
delete p;
return SUCCESS;
}
else
{
}
}
}
return NOT_FOUND;
}
int TsuPod::getNumSongs() //calculates number of songs, returns int value
{
SongNode *p1 = songs;
int i = 0;
while (p1 != NULL)
{
i++;
p1 = p1->next;
}
return i;
}
void TsuPod::shuffle() //shuffles TsuPod song list, void return value
{
srand((unsigned)time(NULL));
for (int j = 0; j < getNumSongs() * 2; j++)
{
int r1 = rand() % getNumSongs();
int r2 = rand() % getNumSongs();
SongNode *p1 = songs;
SongNode *p2 = songs;
for (int i = 0; i < r1; i++)
p1 = p1->next;
for (int i = 0; i < r2; i++)
p2 = p2->next;
Song temp = p1->data;
p1->data = p2->data;
p2->data = temp;
}
cout << endl << " PLAYLIST SHUFFLED" << endl << endl;
}
void TsuPod::sortSongList() //sorts song list by artist, title, and size respectively, void return value
{
for (SongNode *p1 = songs; p1 != NULL; p1 = p1->next)
{
SongNode *small = p1;
for (SongNode *p2 = p1->next; p2 != NULL; p2 = p2->next)
{
if (small->data > p2->data)
{
small = p2;
}
}
if (p1 != small)
{
Song temp = small->data;
small->data = p1->data;
p1->data = temp;
}
}
cout << endl << " PLAYLIST SORTED" << endl;
}
void TsuPod::showSongList() //shows song list, void return value
{
cout << " ___________________________________________________ " << endl << " TsuPod 2.0" << endl << endl;
cout << " Memory ---- Total: " << getTotalMemory() << " MB" << " -- Remaining: " << getRemainingMemory() << " MB" << endl;
SongNode *p = songs;
int i = 0;
while (p != NULL)
{
i++;
cout << endl << " " << i << ". " << p->data.getArtist();
int artistLength = p->data.getArtist().length();
for (int j = 0; j < (24 - artistLength); j++) //This loop is implemented to evenly space the artist from the song
cout << " ";
cout << p->data.getTitle();
int titleLength = p->data.getTitle().length();
for (int j = 0; j < (24 - titleLength); j++) //This loop is implemented to evenly space the song title from the song size
cout << " ";
cout << p->data.getSize() << " (MB)" << endl;
p = p->next;
}
cout << endl;
}
TsuPod_Driver.cpp
#include <cstdlib>
#include <iostream>
#include "Song.h"
#include "TsuPod.h"
using namespace std;
int main(int argc, char *argv[])
{
TsuPod t;
Song s1("Animals As Leaders", "Another Year", 4);
int result = t.addSong(s1);
cout << " add result = " << result << endl;
Song s2("Gorillaz", "Stylo", 6);
result = t.addSong(s2);
cout << " add result = " << result << endl;
Song s3("August Burns Red", "Meridian", 6);
result = t.addSong(s3);
cout << " add result = " << result << endl;
Song s4("The Ink Spots", "If I Didn't Care", 7);
result = t.addSong(s4);
cout << " add result = " << result << endl;
Song s5("Beatles", "I Feel Fine", 241);
result = t.addSong(s5);
cout << " add result = " << result << endl;
Song s6("Fine Constant", "Sea", 3);
result = t.addSong(s6);
cout << " add result = " << result << endl;
Song s7("Human Abstract", "Nocturne", 9);
result = t.addSong(s7);
cout << " add result = " << result << endl;
Song s8("August Burns Red", "Meridian", 4);
result = t.addSong(s8);
cout << " add result = " << result << endl;
Song s9("Frank Sinatra", "My Way", 5);
result = t.addSong(s9);
cout << " add result = " << result << endl;
t.showSongList();
t.shuffle();
t.showSongList();
t.sortSongList();
t.showSongList();
result = t.removeSong(s1);
cout << " delete result = " << result << endl;
result = t.removeSong(s2);
cout << " delete result = " << result << endl;
result = t.removeSong(s3);
cout << " delete result = " << result << endl;
t.showSongList();
result = t.removeSong(s4);
cout << " delete result = " << result << endl;
result = t.removeSong(s5);
cout << " delete result = " << result << endl;
result = t.removeSong(s6);
cout << " delete result = " << result << endl;
result = t.removeSong(s7);
cout << " delete result = " << result << endl;
result = t.removeSong(s8);
cout << " delete result = " << result << endl;
result = t.removeSong(s9);
cout << " delete result = " << result << endl;
t.showSongList();
cout << " memory = " << t.getRemainingMemory() << endl << endl << endl << endl;
for (int i = 1; i < 33; i++) //tests to ensure that user cannot add a song when there is not enough space available
{
Song s1("August Burns Red", "Meridian", i);
result = t.addSong(s1);
cout << " add result = " << result << endl;
}
t.showSongList();
cin.get();
return EXIT_SUCCESS;
Debugging Info From Linux Terminal
Program received signal SIGSEGV, Segmentation fault.
0x0000000000402d50 in Song::getSize() const ()
(gdb) backtrace
#0 0x0000000000402d50 in Song::getSize() const ()
#1 0x00000000004024ac in TsuPod::getRemainingMemory() ()
#2 0x00000000004024fb in TsuPod::addSong(Song const&) ()
#3 0x000000000040112e in main ()
I don't see any sign of TsuPod::songs being initialized. There is no guarantee that it's going to be NULL in the empty list case, so your
while (p != NULL)
test in TsuPod::getRemainingMemory() may pass with an insane value from the stack and blow up when you use p on the next line.
I recommend
TsuPod::TsuPod():songs(NULL) //default constructor
{
memSize = MAX_SIZE;
}
TsuPod::TsuPod(int _size):songs(NULL) //constructor for when user specifies their prefered memory size, prevents input of a size greater than MAX_SIZE or less than 0
{
if (_size > MAX_SIZE || _size <= 0)
memSize = MAX_SIZE;
else
memSize = _size;
}
to ensure that songs starts with your end of list condition.
Also, consider using std::list to do your list management in place of the roll-your-own linked list.

Largest element of list

I need to find the largest element in the list. In the following code unsubscribed items and ordered them. How to find the last element of list? I think that I need add one more function void maksimum(), but I'm having trouble with that.
#include <iostream>
#include <string>
#include <time.h>
#include <conio.h>
#include <cstdlib>
using namespace std;
struct element
{
int number;
element* next;
element();
};
element::element()
{
next = NULL;
}
struct list
{
element* first;
void fill_list(int number);
void segregate();
void show_list();
void maksimum();
list();
};
list::list()
{
first = NULL;
}
void list::fill_list(int number)
{
element *nowy = new element;
nowy->number = number;
if(first == 0)
{
first = nowy;
}
else
{
element* temp = first;
while(temp->next)
{
temp = temp->next;
}
temp->next = nowy;
}
}
void list::show_list()
{
element* temp = first;
if(temp == 0)
{
cout << "List is empty." << endl;
cout << "No smallest element " << endl;
cout << "No largest element" << endl;
}
else
{
while(temp)
{
cout << temp->number << endl;
temp = temp->next;
}
cout << "the smallest element: : " << first->number << endl;
if(first->next == 0)
{
cout << "Largest element = Smallest element :)" << endl;
}
}
}
void list::segregate()
{
element* new_first = NULL;
element* prv;
element* temp;
element* maks;
while(first)
{
maks = first;
prv = NULL;
temp = first;
while(temp->next)
{
if(temp->next->number > maks->number)
{
prv = temp;
maks = temp->next;
}
temp=temp->next;
}
if (prv)
{
prv->next = maks->next;
}
else
{
first = maks->next;
}
maks->next = new_first;
new_first = maks;
}
first = new_first;
}
int main()
{
int n=0;
int number=0;
list* base = new list;
cout << "Size of list: " << endl;
cin >> n;
for(int i = 0; i < n; i++)
{
cout << "No " << i+1 << ": ";
cin >> number;
base->fill_list(number);
}
base->segregate();
base->show_list();
//base->maksimum();
delete(base);
return 0;
}
How can I do that?
ok. you're right, but I thought that my code shows my work. not matter :)
i solved my problem. My function: ^^
void list::show_list()
{
element * temp = first;
if( temp == 0 )
{
cout << "List is empty." << endl;
cout << "No smallest element " << endl;
cout << "No largest element" << endl;
}
else
{
while( temp->next != 0 )
{
temp = temp->next;
}
cout << "The largest element: " << temp->number << endl;
cout << "The smallest element: " << first->number << endl;
}
}