node array declaration - c++

I am trying to initialize a node array in the node class, they are private members:
#include<iostream>
#include<string>
using namespace std;
class Data
{
public:
long data;
Data(long dd)
{
data=dd;
}
void displaydata()
{
cout<<data <<" "<<endl;
}
};
class node
{
//these are what i have changed
const static int order=4;
int numitems;
node *parent;
vector<node>childarray(order);
vector<Data>itemarray(order-1);
};
but unfortunately it does not compile, the errors are:
1>c:\users\dato\documents\visual studio 2010\projects\234_tree\234_tree\234_tree.cpp(26): error C2061: syntax error : identifier 'order'
1>c:\users\dato\documents\visual studio 2010\projects\234_tree\234_tree\234_tree.cpp(27): error C2061: syntax error : identifier 'order'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
From the following java code.
class DataItem
{
public long dData; // one data item
//--------------------------------------------------------------
public DataItem(long dd) // constructor
{ dData = dd; }
//--------------------------------------------------------------
public void displayItem() // display item, format “/27”
{ System.out.print(“/”+dData); }
//--------------------------------------------------------------
} // end class DataItem
////////////////////////////////////////////////////////////////
class Node
{
private static final int ORDER = 4;
private int numItems;
private Node parent;
private Node childArray[] = new Node[ORDER];
private DataItem itemArray[] = new DataItem[ORDER-1];
// -------------------------------------------------------------
// connect child to this node
public void connectChild(int childNum, Node child)
{
childArray[childNum] = child;
if(child != null)
child.parent = this;
}
// -------------------------------------------------------------
// disconnect child from this node, return it
public Node disconnectChild(int childNum)
{
Node tempNode = childArray[childNum];
childArray[childNum] = null;
return tempNode;
}
// -------------------------------------------------------------
public Node getChild(int childNum)
{ return childArray[childNum]; }
// -------------------------------------------------------------
public Node getParent()
{ return parent; }
// -------------------------------------------------------------
public boolean isLeaf()
Java Code for a 2-3-4 Tree 479
LISTING 10.1 Continued
{ return (childArray[0]==null) ? true : false; }
// -------------------------------------------------------------
public int getNumItems()
{ return numItems; }
// -------------------------------------------------------------
public DataItem getItem(int index) // get DataItem at index
{ return itemArray[index]; }
// -------------------------------------------------------------
public boolean isFull()
{ return (numItems==ORDER-1) ? true : false; }
// -------------------------------------------------------------
public int findItem(long key) // return index of
{ // item (within node)
for(int j=0; j<ORDER-1; j++) // if found,
{ // otherwise,
if(itemArray[j] == null) // return -1
break;
else if(itemArray[j].dData == key)
return j;
}
return -1;
} // end findItem
// -------------------------------------------------------------
public int insertItem(DataItem newItem)
{
// assumes node is not full
numItems++; // will add new item
long newKey = newItem.dData; // key of new item
for(int j=ORDER-2; j>=0; j--) // start on right,
{ // examine items
if(itemArray[j] == null) // if item null,
continue; // go left one cell
else // not null,
{ // get its key
long itsKey = itemArray[j].dData;
if(newKey < itsKey) // if it’s bigger
itemArray[j+1] = itemArray[j]; // shift it right
else
{
itemArray[j+1] = newItem; // insert new item
Please help me to convert code easily, do I have to declare the order as public? I have tried but it does not work, I have also tried declaration of order outside of the class, like
const int node::order=4
but have had no success yet, what is the problem? I need array which holds members, size should be order or 4. When I was reading book, author said what you need while writing java code in C++ from this book, it says pointer, so I have added pointer, but no success yet.

The lines
node *childarray[]=new node[order];
Data *itemarray[]=new Data[order-1];
are in error here. Beside that you can not assign like this in the class, you also have the declaration wrong. You are declaring e.g. childarray to be an array of pointers, but you are creating it as a simple array. Change declarations to
node *childarray;
Data *itemarray;
To actually do the allocation you have to do it in a constructor.
However, I really recommend you use std::array (or possibly std::vector) instead.
Edit: Using std::array:
struct node
{
static const int ORDER = 4;
int numitems;
node* parent;
std::array<node*, ORDER> childarray;
std::array<Data*, ORDER - 1> itemarray;
node()
: numitems{0},
parent{nullptr},
childarray{{nullptr}},
itemarray{{nullptr}}
{ }
};
Now childarray and itemarray are arrays with ORDER and ORDER - 1 (respectively) number of pointers, all initialized to nullptr (what NULL should now).

Related

Correctly managing pointers in C++ Quadtree implementation

I'm working on a C++ quadtree implementation for collision detection. I tried to adapt this Java implementation to C++ by using pointers; namely, storing the child nodes of each node as Node pointers (code at the end). However, since my understanding of pointers is still rather lacking, I am struggling to understand why my Quadtree class produces the following two issues:
When splitting a Node in 4, the debugger tells me that all my childNodes entries are identical to the first one, i.e., same address and bounds.
Even if 1. is ignored, I get an Access violation reading location 0xFFFFFFFFFFFFFFFF, which I found out is a consequence of the childNode pointees being deleted after the first split, resulting in undefined behaviour.
My question is: what improvements should I make to my Quadtree.hpp so that each Node can contain 4 distinct child node pointers and have those references last until the quadtree is cleared?
What I have tried so far:
Modifying getChildNode according to this guide and using temporary variables in split() to avoid all 4 entries of childNodes to point to the same Node:
void split() {
for (int i = 0; i < 4; i++) {
Node temp = getChildNode(level, bounds, i + 1);
childNodes[i] = &(temp);
}
}
but this does not solve the problem.
This one is particularly confusing. My initial idea was to just store childNodes as Nodes themselves, but turns out that cannot be done while we're defining the Node class itself. Hence, it looks like the only way to store Nodes is by first creating them and then storing pointers to them as I tried to do in split(), yet it seems that those will not "last" until we've inserted all the objects since the pointees get deleted (run out of scope) and we get the aforementioned undefined behaviour. I also thought of using smart pointers, but that seems to only overcomplicate things.
The code:
Quadtree.hpp
#pragma once
#include <vector>
#include <algorithm>
#include "Box.hpp"
namespace quadtree {
class Node {
public:
Node(int p_level, quadtree::Box<float> p_bounds)
:level(p_level), bounds(p_bounds)
{
parentWorld = NULL;
}
// NOTE: mandatory upon Quadtree initialization
void setParentWorld(World* p_world_ptr) {
parentWorld = p_world_ptr;
}
/*
Clears the quadtree
*/
void clear() {
objects.clear();
for (int i = 0; i < 4; i++) {
if (childNodes[i] != nullptr) {
(*(childNodes[i])).clear();
childNodes[i] = nullptr;
}
}
}
/*
Splits the node into 4 subnodes
*/
void split() {
for (int i = 0; i < 4; i++) {
childNodes[i] = &getChildNode(level, bounds, i + 1);;
}
}
/*
Determine which node the object belongs to. -1 means
object cannot completely fit within a child node and is part
of the parent node
*/
int getIndex(Entity* p_ptr_entity) {
quadtree::Box<float> nodeBounds;
quadtree::Box<float> entityHitbox;
for (int i = 0; i < 4; i++) {
nodeBounds = childNodes[i]->bounds;
ComponentHandle<Hitbox> hitbox;
parentWorld->unpack(*p_ptr_entity, hitbox);
entityHitbox = hitbox->box;
if (nodeBounds.contains(entityHitbox)) {
return i;
}
}
return -1; // if no childNode completely contains Entity Hitbox
}
/*
Insert the object into the quadtree. If the node
exceeds the capacity, it will split and add all
objects to their corresponding nodes.
*/
void insertObject(Entity* p_ptr_entity) {
if (childNodes[0] != nullptr) {
int index = getIndex(p_ptr_entity);
if (index != -1) {
(*childNodes[index]).insertObject(p_ptr_entity); // insert in child node
return;
}
}
objects.push_back(p_ptr_entity); // add to parent node
if (objects.size() > MAX_OBJECTS && level < MAX_DEPTH) {
if (childNodes[0] == nullptr) {
split();
}
int i = 0;
while (i < objects.size()) {
int index = getIndex(objects[i]);
if (index != -1)
{
Entity* temp_entity = objects[i];
{
// remove i-th element of the vector
using std::swap;
swap(objects[i], objects.back());
objects.pop_back();
}
(*childNodes[index]).insertObject(temp_entity);
}
else
{
i++;
}
}
}
}
/*
Return all objects that could collide with the given object
*/
std::vector<Entity*> retrieve(Entity* p_ptr_entity, std::vector<Entity*> returnObjects) {
int index = getIndex(p_ptr_entity);
if (index != -1 && childNodes[0] == nullptr) {
(*childNodes[index]).retrieve(p_ptr_entity, returnObjects);
}
returnObjects.insert(returnObjects.end(), objects.begin(), objects.end());
return returnObjects;
}
World* getParentWorld() {
return parentWorld;
}
private:
int MAX_OBJECTS = 10;
int MAX_DEPTH = 5;
World* parentWorld; // used to unpack entities
int level; // depth of the node
quadtree::Box<float> bounds; // boundary of nodes in the game's map
std::vector<Entity*> objects; // list of objects contained in the node: pointers to Entitites in the game
Node* childNodes[4];
quadtree::Box<float> getQuadrantBounds(quadtree::Box<float> p_parentBounds, int p_quadrant_id) {
quadtree::Box<float> quadrantBounds;
quadrantBounds.width = p_parentBounds.width / 2;
quadrantBounds.height = p_parentBounds.height / 2;
switch (p_quadrant_id) {
case 1: // NE
quadrantBounds.top = p_parentBounds.top;
quadrantBounds.left = p_parentBounds.width / 2;
break;
case 2: // NW
quadrantBounds.top = p_parentBounds.top;
quadrantBounds.left = p_parentBounds.left;
break;
case 3: // SW
quadrantBounds.top = p_parentBounds.height / 2;
quadrantBounds.left = p_parentBounds.left;
break;
case 4: // SE
quadrantBounds.top = p_parentBounds.height / 2;
quadrantBounds.left = p_parentBounds.width / 2;
break;
}
return quadrantBounds;
}
Node& getChildNode(int parentLevel, Box<float> parentBounds, int quadrant) {
static Node temp = Node(parentLevel + 1, getQuadrantBounds(parentBounds, quadrant));
return temp;
}
};
}
Where Box is just a helper class that contains some helper methods for rectangular shapes and collision detection. Any help would be greatly appreciated!

Need to reference and update value from nested class C++

Bear with me, I'm new to C++. I'm trying to update a value which is stored in a vector, but I'm getting this error:
non-const lvalue reference to type 'Node'
I'm using a simple wrapper around std::vector so I can share methods like contains and others (similar to how the ArrayList is in Java).
#include <vector>
using namespace std;
template <class T> class NewFrames {
public:
// truncated ...
bool contains(T data) {
for(int i = 0; i < this->vec->size(); i++) {
if(this->vec->at(i) == data) {
return true;
}
}
return false;
}
int indexOf(T data) {
for(int i = 0; i < this->vec->size(); i++) {
if(this->vec->at(i) == data) {
return i;
}
}
return -1;
}
T get(int index) {
if(index > this->vec->size()) {
throw std::out_of_range("Cannot get index that exceeds the capacity");
}
return this->vec->at(index);
}
private:
vector<T> *vec;
};
#endif // A2_NEWFRAMES_H
The class which utilizes this wrapper is defined as follows:
#include "Page.h"
#include "NewFrames.h"
class Algo {
private:
typedef struct Node {
unsigned reference:1;
int data;
unsigned long _time;
Node() { }
Node(int data) {
this->data = data;
this->reference = 0;
this->_time = (unsigned long) time(NULL);
}
} Node;
unsigned _faults;
Page page;
NewFrames<Node> *frames;
};
I'm at a point where I need to reference one of the Node objects inside of the vector, but I need to be able to change reference to a different value. From what I've found on SO, I need to do this:
const Node &n = this->frames->get(this->frames->indexOf(data));
I've tried just using:
Node n = this->frames->get(this->frames->indexOf(data));
n.reference = 1;
and then viewing the data in the debugger, but the value is not updated when I check later on. Consider this:
const int data = this->page.pages[i];
const bool contains = this->frames->contains(Node(data));
Node node = this->frames->get(index);
for(unsigned i = 0; i < this->page.pages.size(); i++) {
if(node == NULL && !contains) {
// add node
} else if(contains) {
Node n = this->frames->get(this->frames->indexOf(data));
if(n.reference == 0) {
n.reference = 1;
} else {
n.reference = 0;
}
} else {
// do other stuff
}
}
With subsequent passes of the loop, the node with that particular data value is somehow different.
But if I attempt to change n.reference, I'll get an error because const is preventing the object from changing. Is there a way I can get this node so I can change it? I'm coming from the friendly Java world where something like this would work, but I want to know/understand why this doesn't work in C++.
Node n = this->frames->get(this->frames->indexOf(data));
n.reference = 1;
This copies the Node from frames and stores the copy as the object n. Modifying the copy does not change the original node.
The simplest "fix" is to use a reference. That means changing the return type of get from T to T&, and changing the previous two lines to
Node& n = this->frames->get(this->frames->indexOf(data));
n.reference = 1;
That should get the code to work. But there is so much indirection in the code that there are likely to be other problems that haven't shown up yet. As #nwp said in a comment, using vector<T> instead of vector<T>* will save you many headaches.
And while I'm giving style advice, get rid of those this->s; they're just noise. And simplify the belt-and-suspenders validity checks: when you loop from 0 to vec.size() you don't need to check that the index is okay when you access the element; change vec.at(i) to vec[i]. And in get, note that vec.at(index) will throw an exception if index is out of bounds, so you can either skip the initial range check or keep the check (after fixing it so that it checks the actual range) and, again, use vec[index] instead of vec.at(index).

C++ pointer linked list

So I am new to c++ sorry if this is not to clear.
I have a class:
class Item
{
int noItem;
int qItem;
public:
Item(int noItem, int qItem)
{
this->noItem = noItem;
this->qItem = qItem;
}
int getNoItem()
{
return noItem;
}
int getQntItem()
{
return qItem;
}
};
Then the following class:
class Element
{
public:
Element()
{
data = NULL;
}
//to set and access data hold in node
void setElement(Item *data)
{
this->data = data;
}
Item* getElement(void)
{
return(data);
}
private:
Item *data;
};
This one also:
class ListeChainee
{
public:
ListeChainee()
{
courant = NULL;
}
void ajoutListe(Item *data)
{
Element *newData;
//set data
newData->setElement(data);
//check if list is empty
if( courant == NULL)
{
//set current pointer
courant = newData;
}
}
//get data from element pointed at by current pointer
Item* elementCourant(void)
{
if(courant != NULL)
{
return courant->getElement();
}
else
{
return NULL;
}
}
private:
//data members
Element *courant; //pointer to current element in list
};
The code is missing some stuff for other things, but my problem is this:
int main(int argc, char* argv[])
{
ListeChainee listeCH;
Item i1(123,456);
listeCH.ajoutListe(&i1);
cout << listeCH.elementCourant()->getNoItem();
system("pause");
return 0;
}
I expect 123 to be outputted, but I see some other number. Not sure why.
Thanks.
Your Element *newData doesn't have an instance of Element class, so it will crash when you try to access the instance pointed by newData.
Try to change Element *newData; to Element *newData = new Element;.
ps.: Don't forget to delete it when you don't need the instance any more.
This method is writing to uninitialized memory:
void ajoutListe(Item *data)
{
Element *new;
//set data
new->setElement(data); // Right here, "new" is an uninitialized pointer
//check if list is empty
if( courant == NULL)
{
//set current pointer
courant = new;
}
}
I'm surprised this compiles (does it?). This code should also crash.
The strange number you're getting is surely some random part of memory. You may want to think more about memory management -- there are numerous problems here. When ajoutListe is called, why does the courant member only get set if it's NULL? Do we just leak the new Element? How do we actually traverse this list?

Hash table implementation in C++

I am trying the following code for Hash table implementation in C++. The program compiles and accepts input and then a popup appears saying " the project has stopped working and windows is checking for a solution to the problem. I feel the program is going in the infinite loop somewhere. Can anyone spot the mistake?? Please help!
#include <iostream>
#include <stdlib.h>
#include <string>
#include <sstream>
using namespace std;
/* Definitions as shown */
typedef struct CellType* Position;
typedef int ElementType;
struct CellType{
ElementType value;
Position next;
};
/* *** Implements a List ADT with necessary functions.
You may make use of these functions (need not use all) to implement your HashTable ADT */
class List{
private:
Position listHead;
int count;
public:
//Initializes the number of nodes in the list
void setCount(int num){
count = num;
}
//Creates an empty list
void makeEmptyList(){
listHead = new CellType;
listHead->next = NULL;
}
//Inserts an element after Position p
int insertList(ElementType data, Position p){
Position temp;
temp = p->next;
p->next = new CellType;
p->next->next = temp;
p->next->value = data;
return ++count;
}
//Returns pointer to the last node
Position end(){
Position p;
p = listHead;
while (p->next != NULL){
p = p->next;
}
return p;
}
//Returns number of elements in the list
int getCount(){
return count;
}
};
class HashTable{
private:
List bucket[10];
int bucketIndex;
int numElemBucket;
Position posInsert;
string collision;
bool reportCol; //Helps to print a NO for no collisions
public:
HashTable(){ //constructor
int i;
for (i=0;i<10;i++){
bucket[i].setCount(0);
}
collision = "";
reportCol = false;
}
int insert(int data){
bucketIndex=data%10;
int col;
if(posInsert->next==NULL)
bucket[bucketIndex].insertList(data,posInsert);
else { while(posInsert->next != NULL){
posInsert=posInsert->next;
}
bucket[bucketIndex].insertList(data,posInsert);
reportCol=true;}
if (reportCol==true) col=1;
else col=0;
numElemBucket++;
return col ;
/*code to insert data into
hash table and report collision*/
}
void listCollision(int pos){
cout<< "("<< pos<< "," << bucketIndex << "," << numElemBucket << ")"; /*codeto generate a properly formatted
string to report multiple collisions*/
}
void printCollision();
};
int main(){
HashTable ht;
int i, data;
for (i=0;i<10;i++){
cin>>data;
int abc= ht.insert(data);
if(abc==1){
ht.listCollision(i);/* code to call insert function of HashTable ADT and if there is a collision, use listCollision to generate the list of collisions*/
}
//Prints the concatenated collision list
ht.printCollision();
}}
void HashTable::printCollision(){
if (reportCol == false)
cout <<"NO";
else
cout<<collision;
}
The output of the program is the point where there is a collision in the hash table, thecorresponding bucket number and the number of elements in that bucket.
After trying dubbuging, I come to know that, while calling a constructor you are not emptying the bucket[bucketIndex].
So your Hash Table constructor should be as follow:
HashTable(){ //constructor
int i;
for (i=0;i<10;i++){
bucket[i].setCount(0);
bucket[i].makeEmptyList(); //here we clear for first use
}
collision = "";
reportCol = false;
}
//Creates an empty list
void makeEmptyList(){
listHead = new CellType;
listHead->next = NULL;
}
what you can do is you can get posInsert using
bucket[bucketIndex].end()
so that posInsert-> is defined
and there is no need to
while(posInsert->next != NULL){
posInsert=posInsert->next;
because end() function is doing just that so use end() function

Creating an n array with a linked list of ints

I recently made an 26array and tried to simulate a dictionary.
I can't seem to figure out how to make this. I've tried to work with passing in a linkedlist of ints instead of a string. My current code creates 26 nodes(a-z) and then each of those nodes has 26 nodes(a-z). I would like to implement a way to do this with ints, say (1-26). These int nodes will represent items, and the linkedlist of ints I want to pass in will contain a set of ints that I want represented in the tree similar to a string.
Example: pass in the set {1, 6 , 8}, instead of a string such as "hello"
#include <iostream>
using namespace std;
class N26
{
private:
struct N26Node
{
bool isEnd;
struct N26Node *children[26];
}*head;
public:
N26();
~N26();
void insert(string word);
bool isExists(string word);
void printPath(char searchKey);
};
N26::N26()
{
head = new N26Node();
head->isEnd = false;
}
N26::~N26()
{
}
void N26::insert(string word)
{
N26Node *current = head;
for(int i = 0; i < word.length(); i++)
{
int letter = (int)word[i] - (int)'a';
if(current->children[letter] == NULL)
{
current->children[letter] = new N26Node();
}
current = current->children[letter];
}
current->isEnd = true;
}
/* Pre: A search key
* Post: True is the search key is found in the tree, otherwise false
* Purpose: To determine if a give data exists in the tree or not
******************************************************************************/
bool N26::isExists(string word)
{
N26Node *current = head;
for(int i=0; i<word.length(); i++)
{
if(current->children[((int)word[i]-(int)'a')] == NULL)
{
return false;
}
current = current->children[((int)word[i]-(int)'a')];
}
return current->isEnd;
}
class N26
{
private:
N26Node newNode(void);
N26Node *mRootNode;
...
};
N26Node *newNode(void)
{
N26Node *mRootNode = new N26Node;
mRootNode = NULL;
mRootNode->mData = NULL;
for ( int i = 0; i < 26; i++ )
mRootNode->mAlphabet[i] = NULL;
return mRootNode;
}
Ah! My eyes!
Seriously, you are attempting something much too advanced. Your code is full of bugs and cannot work as intended. Tinkering will not help, you must go back to basics of pointers and linked lists. Study the basics and do not attempt anything like a linked list of linked lists until you understand what is wrong with the code above.
I'll give you some hints: "memory leak", "dangling pointer", "type mismatch", "undefined behavior".
I didnt quite use linked lists, but I managed to get it working using arrays.
/* *** Author: Jamie Roland
* Class: CSI 281
* Institute: Champlain College
* Last Update: October 31, 2012
*
* Description:
* This class is to implement an n26 trie. The
* operations
* available for this impementation are:
*
* 1. insert
* 2. isEmpty
* 3. isExists
* 4. remove
* 5. showInOrder
* 6. showPreOrder
* 7. showPostOrder
*
* Certification of Authenticity:
* I certify that this assignment is entirely my own work.
**********************************************************************/
#include <iostream>
using namespace std;
class N26
{
private:
struct N26Node
{
bool isEnd;
struct N26Node *children[26];
}*head;
public:
N26();
~N26();
void insert(int word[]);
bool isExists(int word[]);
void printPath(char searchKey);
};
N26::N26()
{
head = new N26Node();
head->isEnd = false;
}
N26::~N26()
{
}
void N26::insert(int word[])
{
int size = sizeof word/sizeof(int);
N26Node *current = head;
for(int i = 0; i < size; i++)
{
int letter = word[i] - 1;
if(current->children[letter] == NULL)
{
current->children[letter] = new N26Node();
}
current = current->children[letter];
}
current->isEnd = true;
}
/* Pre: A search key
* Post: True is the search key is found in the tree, otherwise false
* Purpose: To determine if a give data exists in the tree or not
******************************************************************************/
bool N26::isExists(int word[])
{
int size = sizeof word/sizeof(int);
N26Node *current = head;
for(int i=0; i<size; i++)
{
if(current->children[(word[i]-1)] == NULL)
{
return false;
}
current = current->children[(word[i]-1)];
}
return current->isEnd;
}