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 6 years ago.
Improve this question
I can't figure out why my virtual function is not being overridden, when looking up examples online I can't spot what I'm doing wrong, I must be missing something.
Base Class
class HashTable {
// removed some unrelated functions and data to keep this page short
void Insert(int key, HashTable *htable)
{
int pos = Find(key, htable);
if (htable->table[pos].info != Legitimate)
{
htable->table[pos].info = Legitimate;
int rKey = Reverse(key);
htable->table[pos].element = rKey;
}
}
virtual int Find(int key, HashTable *htable)
{
return 0;
}
};
Children Class
class SingleHash : public HashTable {
int Find(int key, HashTable *htable)
{
int hashVal = HashFunc1(key, htable->size);
while (htable->table[hashVal].info != Empty &&
htable->table[hashVal].element != key)
{
hashVal = hashVal;
hashVal = hashVal % htable->size;
prob = prob + 1;
}
trackProbes(prob);
return hashVal;
}
};
class DoubleHash : public HashTable {
int Find(int key, HashTable *htable)
{
int hashVal = HashFunc1(key, htable->size);
int stepSize = HashFunc2(key, htable->size);
while (htable->table[hashVal].info != Empty &&
htable->table[hashVal].element != key)
{
hashVal = hashVal + stepSize;
hashVal = hashVal % htable->size;
prob = prob + 1;
}
trackProbes(prob);
return hashVal;
}
};
What my main is looking like
int main()
{
int value, size, pos, i = 1;
int choice = 1;
HashTable *htable = new SingleHash;
cin >> value;
htable->Insert(value, htable);
// more unrelated stuff
}
When I run my program it just returns what's in the base class (0) when I make a call to Insert.
There are compile errors in code you provided like functions your not declared public for basics.
I tried to make MCVE for you, and it seems to be working fine.
#include <iostream>
using namespace std;
class HashTable {
public:
void Insert(int x) {
Find(x);
}
virtual int Find(int x) {
cout<<"base hash find \n";
return x; }
};
class SingleHash : public HashTable {
public:
int Find(int x) {
cout<<"single hash find \n";
return x*2;
}
};
class DoubleHash : public HashTable {
public:
int Find(int x) {
cout<<"DOuble hash find \n";
return x*3; }
};
int main(int argc, char** argv)
{
int value;
HashTable *hsingle = new SingleHash;
cin >> value;
hsingle->Insert(value);
HashTable *hdouble = new DoubleHash;
hdouble->Insert(value);
return 0;
}
The output is :
single hash find
DOuble hash find
Related
I'm pretty new to C++ and am trying to teach myself how to implement a hash table(I know I could use unordered_map, but I'm challenging myself). Right now I have a vector of structs(cell) that holds person-specific information. I have a PrintTable function that I want to use to print out each struct member of every item in the table. However, I can't seem to access the specific members of the struct(cell). What am I doing wrong here?
#include <iostream>
#include <string>
#include <vector>
struct cell
{
std::string name;
int age;
std::string weapon;
};
class HashTable
{
private:
std::vector<cell> *table;
int total_elements;
int getHash(int key)
{
return key % total_elements;
}
public:
HashTable(int n)
{
total_elements = n;
table = new std::vector<cell>[total_elements];
}
void SearchTheTable(int hashIndex);
void AddItem(std::string name, int age, std::string weapon);
void RemoveItem();
void PrintTable();
};
void HashTable::SearchTheTable(int hashIndex)
{
int x = getHash(hashIndex);
std::cout << x;
}
void HashTable::AddItem(std::string name, int age, std::string weapon)
{
cell newCell = { name, age, weapon };
table->push_back(newCell);
}
void HashTable::RemoveItem()
{
}
void HashTable::PrintTable()
{
for (int i = 0; i < table->size; i++)
{
std::cout << table[i].name; // Right here I get an error that says: class "std::vector<cell, std::allocator<cell>>" has no member "name".
}
}
int main()
{
HashTable theTable(5);
theTable.AddItem("Ryan", 27, "Sword");
theTable.AddItem("Melony", 24, "Axe");
theTable.PrintTable();
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I want to implement the Decorator design pattern. However, my code gives me Segmentation fault error. I tried to compile it using the -g flag and then check it with gdb. gdb shows only that the error is somewhere inside the action method, but I do not understand where and why.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
class CComponent
{
protected:
int * i_array;
int i_size;
public:
CComponent(int i_size)
{
this->i_size=i_size;
i_array= new int[i_size];
for(int i=0; i<i_size; i++)
{
i_array[i]=0;
}
}
virtual int action() = 0;
~CComponent()
{
delete i_array;
}
int get_i_size()
{
return i_size;
}
int get_array_at(int index)
{
return i_array[index];
}
};
class CConcreteCComponent : public CComponent
{
public:
CConcreteCComponent(int i_size) : CComponent(i_size) { }
int action()
{
for(int i=0; i<i_size; i++)
{
i_array[i] = rand() % 100;
cout<< i_array[i] << " " << endl;
}
return 0;
}
};
class Decorator : public CComponent
{
protected:
CComponent * c;
public:
Decorator(int i_size) : CComponent(i_size)
{
c = new CConcreteCComponent(100);
}
int action()
{
return c->action();
}
};
class CConcreteDecorator3 : public Decorator
{
public:
CConcreteDecorator3(int i_size) : Decorator(i_size)
{
}
int action()
{
int w = action();
for(int i=0; i<c->get_i_size(); i++)
if(c->get_array_at(i) % 2 == 0)
return w;
return w + 50;
}
};
class CConcreteDecorator1 : public Decorator
{
public:
CConcreteDecorator1(int i_size) : Decorator(i_size)
{
}
int action()
{
int w = action();
if(c->get_array_at(0) == 0 && c->get_array_at(i_size -1) == 0)
return w + 100;
return w;
}
};
class CConcreteDecorator2 : public Decorator
{
public:
CConcreteDecorator2(int i_size) : Decorator(i_size)
{
}
int action()
{
int w = action();
if(c->get_i_size() > 7)
return w + 150;
return w;
}
};
int main()
{
Decorator * d = new CConcreteDecorator3(100);
Decorator * d2 = new CConcreteDecorator1(100);
Decorator * d3 = new CConcreteDecorator2(100);
int res;
res = d->action();
cout << "res :" << res << endl;
return 0;
}
The reason is an infinite recusion.
In CConcreteDecorator3 in action method instead of:
int w = action();
You should probably use:
int w = Decorator::action();
Furthermore...
Your Decorator class leaks. You have no destructor with a delete.
It is considered good practice to use a std::vector<int> instead int * i_array and a std::unique_ptr for CComponent * c; Dont bother using new/delete unless you cannot avoid it.
Your CComponent needs a virtual destructor. You'll find a lot of explanations if you google polymorphism and virtual destructor.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i am new to c++ and i am currently trying to write a program that uses main to call functions which are seperately written and i tried to write the definitions for the header file declarations and i am getting errors with some functions which i have marked in the code
Store.hpp
#ifndef STORE_HPP
#define STORE_HPP
class Product;
class Customer;
#include<string>
#include "Customer.hpp"
#include "Product.hpp"
class Store
{
private:
std::vector<Product*> inventory;
std::vector<Customer*> members;
public:
void addProduct(Product* p);
void addMember(Customer* c);
Product* getProductFromID(std::string);
Customer* getMemberFromID(std::string);
void productSearch(std::string str);
void addProductToMemberCart(std::string pID, std::string mID);
void checkOutMember(std::string mID);
};
#endif
i am having trouble writing the code for that function help me
store.cpp
#include <iostream>
#include <string.h>
#include "Customer.hpp"
#include "Store.hpp"
#include "Product.hpp"
using namespace std;
string id;
void Store::addProduct(Product* p) //error 1 no matching function
{
Product* p(std::string id, std::string t, std::string d, double p, int qa);
inventory.push_back(p);
}
void Store:: addMember(Customer* c)
{
members.push_back(c->getAccountID());
}
Product* Store::getProductFromID(std::string id)
{
for(int i = 0; i < inventory.size(); i++)
{
Product* p=inventory.at(i);
if(p->getIdCode()= id)
{
return p;
}
}
return NULL;
}
Customer* Store:: getMemberFromID(std::string id)
{
for(int i = 0; i < members.size(); i++)
{
Customer* c = members.at(i);
if(c->getAccountID() == id)
{
return c;
}
}
return NULL;
}
void std::Store productSearch(std::string str)
{
for(int i = 0; i < inventory.size(); i++)
{
if(inventory[i] == str)
{
Product stud(inventory[i],inventory[i+1],inventory[i+2],inventory[i+3],inventory[i+4]);
cout<<getIdCode();
cout<<getTitle();
cout<<getDescription();
cout<<getPrice();
cout<<getQuantityAvailable();
}
}
}
void addProductToMemberCart(std::string pID, std::string mID)
{
cout<<"adding to cart"<<endl;
getMemberFromID(mID)->addProductToCart(pID);
}
void checkOutMember(std::string mID)
{
Customer* c=getAccountID(mID)
mID=getMemberFromID(std::string mID);
if(mID=="NULL")
{
cout<<mID<<"is not found"<<endl;
}
}
customer.hpp
#ifndef CUSTOMER_HPP
#define CUSTOMER_HPP
#include<vector>
#include "Product.hpp"
class Customer
{
private:
std::vector<std::string> cart;
std::string name;
std::string accountID;
bool premiumMember;
public:
Customer(std::string n, std::string a, bool pm);
std::string getAccountID();
//std::vector getCart();
void addProductToCart(std::string);
bool isPremiumMember();
void emptyCart();
};
#endif
product.hpp
#ifndef PRODUCT_HPP
#define PRODUCT_HPP
#include<vector>
class Product
{
private:
std::string idCode;
std::string title;
std::string description;
double price;
int quantityAvailable;
public:
Product(std::string id, std::string t, std::string d, double p, int qa);
std::string getIdCode();
std::string getTitle();
std::string getDescription();
double getPrice();
int getQuantityAvailable();
void decreaseQuantity();
};
#endif
You code issues lots of warnings and errors as stands.
If you find yourself in this situation and can't figure out what one of them means, try to fix some of the others.
Your main problem is in addProduct, but there are others
using namespace std;
string id; //<---- what's this for?
void Store::addProduct(Product* p) //error 1 no matching function
{
//Product* p(std::string id, std::string t, std::string d, double p, int qa);
//<--- This line had the error and isn't needed
inventory.push_back(p);
}
void Store::addMember(Customer* c)
{
// members.push_back(c->getAccountID()); //<--- this errors too
members.push_back(c);
}
Product* Store::getProductFromID(std::string id)
{
for (size_t i = 0; i < inventory.size(); i++)
{
Product* p = inventory.at(i);
//if (p->getIdCode() = id) //<-- be careful with = and ==
if (p->getIdCode() == id) //<---
{
return p;
}
}
return NULL;
}
Customer* Store::getMemberFromID(std::string id)
{
for (size_t i = 0; i < members.size(); i++)
{
Customer* c = members.at(i);
if (c->getAccountID() == id)
{
return c;
}
}
return NULL;
}
//void std::Store productSearch(std::string str)
void Store::productSearch(std::string str) // <---- note this change too
{
for (size_t i = 0; i < inventory.size(); i++)
{
//if (inventory[i] == str) //<<--------!
if (inventory[i]->getDescription() == str)
{
//Product stud(inventory[i], inventory[i + 1], inventory[i + 2], inventory[i + 3], inventory[i + 4]);
// This is five Products from the inventory, not the i-th product in your invetory
Product stud(*inventory[i]);//<---- I assume
cout << stud.getIdCode();
cout << stud.getTitle();
cout << stud.getDescription();
cout << stud.getPrice();
cout << stud.getQuantityAvailable();
}
}
}
void Store::addProductToMemberCart(std::string pID, std::string mID)//<--- note note std::Store addProductToMemberCart
{
cout << "adding to cart" << endl;
getMemberFromID(mID)->addProductToCart(pID);
}
void Store::checkOutMember(std::string mID)//<---
{
//Customer* c = getAccountID(mID);//<<---?
//mID = getMemberFromID(std::string mID); //<---?
Customer* c = getMemberFromID(mID); //Just this?
if (c == NULL)//<---rather than "NULL" but nullptr might be better
{ // or not using pointers at all
cout << mID << "is not found" << endl;
}
}
So, as part of my assignment in Computer Science, which was to read tweets and put them into a custom Dictionary, I had to, you guessed it, create a dictionary. However, during testing with the dictionary, I encountered an error which I have been unable to fix, despite hours of attempted troubleshooting. I have narrowed it down, and determined that the error lies on line 144, somewhere in the statement cout<<j.get("name").getFront()->getText();, but I have been unable to determine which part of this causes issues, even when breaking it down by parts, except that it begins when I add in the ->getText(), however I heavily suspect that the problem starts earlier on.
I am sorry if I am not too specific, or if I ramble too much, I have just been having trouble with this for a while, and am beginning to get frustrated.
I understand not all the execution or style is the best, so I may ask you to refrain from leaving comments on the way things are done, unless it may directly relate to the problem at hand.
Thank you for any and all help.
/*********************************************************************************************************************
* [REDACTED] *
* CS 101-- Project 4 (Hashing Twitter) *
* This program stores Twitter posts in a hash table * *
*********************************************************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
class tweet {
private:
string create_at;
string text;
string screen_name;
public:
string getCreate_at() {
return create_at;
};
string getText() {
return text;
};
string getScreen_name() {
return screen_name;
};
void setCreate_at(string c) {
create_at=c;
};
void setText(string c) {
text=c;
};
void setScreen_name(string c) {
screen_name=c;
};
};
class LinkedList {
public:
tweet* getFront() {
return top;
};
LinkedList* getNext() {
return next;
};
void setNext(LinkedList* c) {
next = c;
};
void setTweet(tweet c) {
top = &c;
};
void setTweet(tweet* c) {
top = c;
};
void insertFront(tweet c) {
LinkedList temp;
temp.setTweet(top);
temp.setNext(next);
this->setTweet(c);
this->setNext(&temp);
};
tweet* removeFront() {
tweet* temp;
temp = top;
if(next != NULL){
top = next->getFront();
if(next->getNext() != NULL)
next = next->getNext();
}
return temp;
};
private:
tweet* top;
LinkedList* next;
};
class HashTable {
private:
vector<LinkedList> store [256];//access by firstcharacter of name as index of array then search through vector linearly until find key
LinkedList getLinkedList(string c) {
vector<LinkedList> temp=store[(int)c.c_str()[0]];
for(int i =0;i<temp.size();i++) {
if(temp.at(i).getFront()->getScreen_name()==c) {
return temp.at(i); //gets list of tweets
}
};
};
bool keyExists(string c) {
vector<LinkedList> temp = store[(int)c.c_str()[0]];
for(int i =0;i<temp.size();i++) {
if(temp.at(i).getFront()->getScreen_name()==c) {
return true; //gets list of tweets
}
};
return false;
};
void insertTweet(tweet c){
if(keyExists(c.getScreen_name())){
getLinkedList(c.getScreen_name()).insertFront(c);
} else {
LinkedList temp;
temp.setTweet(c);
store[c.getScreen_name().c_str()[0]].push_back(temp);
}
};
public:
void put(tweet c) {
insertTweet(c);
};
LinkedList get(string key) {
return getLinkedList(key);
};
bool contains(string key) {
return keyExists(key);
};
void remove(string key) {
vector<LinkedList> temp=store[key.c_str()[0]];
for(int i =0;i<temp.size();i++) {
if(temp.at(i).getFront()->getScreen_name()==key) {
temp.erase(temp.begin()+i); //gets list of tweets
}
};
};
};
HashTable parser(string filename) {
//backslashes
};
int main(int argc, char *argv[])
{
tweet hello;
hello.setText("hello");
hello.setScreen_name("user");
hello.setCreate_at("10211997");
tweet heyo;
heyo.setText("heyo");
heyo.setScreen_name("name");
heyo.setCreate_at("79912101");
LinkedList jerome;
jerome.insertFront(hello);
cout<<jerome.getFront()->getText()<<endl;
jerome.insertFront(heyo);
cout<<jerome.removeFront()->getText()<<endl;
HashTable j;
j.put(heyo);
cout<<j.get("name").getFront()->getText();
}
You are getting the addresses of temporaries:
void insertFront(tweet c) {
LinkedList temp;
temp.setTweet(top);
temp.setNext(next);
this->setTweet(c); //should be &c, but c is a temporary!
this->setNext(&temp); //temp is a temporary!
};
Also, in HashTable, you need put and insertTweet to have a tweet& parameter.
Finally, still in insertTweet, you should pass the address of c to setTweet.
Note that this code is very fragile, as you will have dangling pointers as soon as the tweet objects go out of scope.
Yes I am still learning C++ and I am trying to create my own Hash.h header with several hash functions (non-cryptic) such as MurmurHash and CityHash. To start this off I just wanted a very basic implementation first. But it is not compiling as I have some memory errors. It is due to adding a entry where data is passed to the class function. Changing to pointers/references gave similar errors and I just can't seem to fix it. Can somebody see what is going wrong such that I know what to look for in the future? Thanks!
//Hash.h
template<class T>
class HashEntry{
private:
int key;
T data;
public:
HashEntry() {};
void putData(T input, int keyVal){
//SEGMENTATION FAULT HAPPENS HERE!!
key = keyVal;
data = input;
}
T getData(){
return data;
}
};
template<class T>
class Hash{
private:
int myFunc;
size_t sizeHash;
HashEntry<T> **table;
public:
Hash(int func, size_t size): myFunc(func), sizeHash(size-1) {
table = new HashEntry<T>*[sizeHash];
for (int i=0;i<sizeHash;i++) table[i] = NULL;
}
int hashFunc(int key){
try{
if (myFunc == 0){
return key % sizeHash;
} else if (myFunc == 1){
//other has func's
} else {string excep = "No such hash function!"; throw excep;}
} catch(string e) {cout << "Hash::hashFunc(): Exception Raised: " << e << endl; exit(0);}
return -1;
}
void addEntry(T data, int key){
int myHash = hashFunc(key);
table[myHash]->putData(data, key);
}
};
Call from main:
Hash<char> *myHash = new Hash<char>(0,10);
myHash->addEntry('s', 11);
return 0;