I am currently learning how to implement a binary search tree, but using a more rudimentary C approach(please no "use classes now"). However, there is a big problem with dynamic memory getting itself deleted. The head value gets updated correctly, however, every other point gets itself deleted. Can anyone help me? Also, it would be nice if you would offer some tips how to tighten up my implementation of the tree. A basic rundown of the program: you input a character and thus you run one of the tree's functions. Mind though, that this implementation is a pure BST, so no balancing. Thank you.
#include <iostream>
struct point{
point* parent, *left, *right;
int val = -1;
};
point* biggest;
point empty;
point search(int pos, bool near, point* loc = biggest){
if(loc->val == pos){
return *loc;
} else if(loc->left->val != -1 and loc->val > pos){
return search(pos, near, loc->left);
} else if(loc->right->val != -1){
return search(pos, near, loc->right);
}
if(near){
return *loc;
} else{
point fail;
return fail;
}
}
void insert(int pos, point* res){
point loc = search(pos, true);
res->val = pos, res->left = &empty, res->right = &empty, res->parent = &loc;
if(loc.val < res->val){
loc.left = res;
} else{
loc.right = res;
}
}
void remove(int pos){
}
int pred(int pos){
point res = search(pos, false);
if(res.val == -1){
return -1;
}
}
int succ(int pos){
point res = search(pos, false);
if(res.val == -1){
return -1;
}
}
void inorder(point* pos = biggest){
if(pos->left->val != -1){
inorder(pos->left);
}
std::cout << pos->val << " ";
if(pos->right->val != -1){
inorder(pos->right);
}
}
int main() {
point start;
start.parent = &empty, start.left = &empty, start.right = ∅
biggest = &start;
char c;
int pos;
do{
std::cin >> c >> pos;
switch (c){
case 'S':
std::cout << search(pos, false).val << std::endl;
break;
case 'I':
if(biggest->val == -1){
start.val = pos;
} else{
point* res = new point;
insert(pos, res);
}
break;
case 'R':
remove(pos);
break;
case 'P':
std::cout << pred(pos) << std::endl;
break;
case 'N':
std::cout << succ(pos) << std::endl;
break;
case 'O':
inorder();
std::cout << std::endl;
break;
}
} while(c != '0');
return 0;
}
Apart from much weirdness in your code I would say that here :
void insert(int pos, point* res){
point loc = search(pos, true);
res->val = pos, res->left = &empty, res->right = ∅
res->parent = &loc; // <=== here
you modify res->parent to point at a local variable loc. After the insert() function returns the point loc does not exist anymore.
Also you are already using classes; C++ structs and classes are pretty much identical ... apart from the default member visibility.
Related
hi so i have this circular queue c++ program i need its display function only displays even inserted numbers only can someone here help please here's the code
i need a way that this program only displays even numbers only i'v been trying to use the %2==0 on some location that might make sense but mostly i get them wrong or empty
.
.
.
.
.
.
#include <iostream>
using namespace std;
int cqueue[5];
int front = -1, rear = -1, n=5;
void insertCQ(int val) {
if ((front == 0 && rear == n-1) || (front == rear+1)) {
cout<<"Queue Overflow \n";
return;
}
if (front == -1) {
front = 0;
rear = 0;
} else {
if (rear == n - 1)
rear = 0;
else
rear = rear + 1;
}
cqueue[rear] = val ;
}
void deleteCQ() {
if (front == -1) {
cout<<"Queue Underflow\n";
return ;
}
cout<<"Element deleted from queue is : "<<cqueue[front]<<endl;
if (front == rear) {
front = -1;
rear = -1;
} else {
if (front == n - 1)
front = 0;
else
front = front + 1;
}
}
void displayCQ() {
int f = front, r = rear;
if (front == -1) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are :\n";
if (f <= r) {
while (f <= r){
cout<<cqueue[f]<<" ";
f++;
}
} else {
while (f <= n - 1) {
cout<<cqueue[f]<<" ";
f++;
}
f = 0;
while (f <= r) {
cout<<cqueue[f]<<" ";
f++;
}
}
cout<<endl;
}
int main() {
int ch, val;
cout<<"1)Insert\n";
cout<<"2)Delete\n";
cout<<"3)Display\n";
cout<<"4)Exit\n";
do {
cout<<"Enter choice : "<<endl;
cin>>ch;
switch(ch) {
case 1:
cout<<"Input for insertion: "<<endl;
cin>>val;
insertCQ(val);
break;
case 2:
deleteCQ();
break;
case 3:
displayCQ();
break;
case 4:
cout<<"Exit\n";
break;
default: cout<<"Incorrect!\n";
}
} while(ch != 4);
return 0;
}
Here's a quick example using std::queue:
#include <iostream>
#include <queue>
int main()
{
// This deque is declared just to more easily instantiate the queue
std::deque<int> deck{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::queue<int> q{deck};
while (!q.empty()) {
if (q.front() % 2 == 0) {
std::cout << q.front() << ' ';
}
q.pop();
}
std::cout << '\n';
}
You were on the right path using mod 2, but everything about your "queue" is not correct. To put it simply, you have not written a queue, and definitely not a circular queue.
Queues are FIFO data structures; first in, first out. Think of it like a tunnel. I will only add elements to one end, and I will only remove elements from the other. Everything in the middle does not matter, except to know the size of the queue. This means that the only visible elements are the first and last. If I want to see the second element of the queue, I must remove the first element.
The code you've written treats your array like a list instead where you have free access to all elements.
It's better to write an actual queue class, and I would hope that if you're writing data structures, that you are able to write a class.
Here's an extremely basic queue class that exhibits the behavior you are asking about. There is nothing circular about it. The word circular implies that your queue should be implemented with a circular linked list and not an array. It's worth noting that it requires at least C++11, but that really shouldn't be a problem today.
IMPORTANT
This code leaves out a lot of necessary error-checking. For example, back() will likely lead to undefined behavior if called on an empty queue, among other things. This was intentional to avoid a flat-out copy/paste being employed because cheating on homework is bad.
#include <array>
#include <iostream>
namespace Q {
class queue {
public:
int &front() { return m_arr[0]; }
int &back() { return m_arr[m_size - 1]; }
void push(int val) {
if (m_size < 5) {
m_arr[m_size] = val;
++m_size;
}
}
// Shifts entire array one to the left
void pop() {
if (m_size > 0) {
for (int i = 1; i < m_size; ++i) {
m_arr[i - 1] = m_arr[i];
}
--m_size;
}
}
bool empty() const { return m_size == 0; }
private:
std::array<int, 5> m_arr = {0};
int m_size = 0;
};
}; // namespace Q
int main() {
Q::queue q;
for (int i = 1; i <= 5; ++i) {
q.push(i);
}
while (!q.empty()) {
if (q.front() % 2 == 0) {
std::cout << q.front() << ' ';
}
q.pop();
}
std::cout << '\n';
}
I'm not too sure if questions of this sort is allowed on stackoverflow but here it goes. I finished up this assignment to calculate reverse polish expressions with a small set of operators. All the tests passed and I have already submitted the assignment. I was wondering if you guys had any suggestions where I could improve on the code that could be applied to my future assignments/projects.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class TheStack
{
public:
void push(double d1);
double pop();
int getNodeTracker();
private:
struct Node
{
double data;
Node* next;
};
Node* bottom = NULL;
Node* top = NULL;
Node* newP = NULL;
int nodeTracker = 0;
};
void TheStack::push(double d1)
{
newP = new Node;
newP->data = d1;
newP->next = NULL;
if (bottom == NULL)
{
bottom = top = newP;
top->next = NULL;
}
else
{
newP->next = top;
top = newP;
}
nodeTracker += 1;
}
double TheStack::pop()
{
Node* tempP;
double tempD;
if (top == NULL)
{
cout << "The stack is empty." << endl;
}
else
{
tempP = top;
tempD = tempP->data;
top = top->next;
delete(tempP);
nodeTracker -= 1;
return(tempD);
}
}
int TheStack::getNodeTracker()
{
return nodeTracker;
}
bool isOperand(string s1);
bool isOperator(string s1);
double operate(string s1, double d1, double d2);
int processor(string str);
bool validString(string str);
int main()
{
// getting user input
string str;
getline(cin, str);
// input loop
while (str != "0")
{
processor(str);
cout << endl;
getline(cin, str);
}
// end program
return 0;
}
bool isOperand(string s1)
{
try
{
stod(s1);
}
catch (...)
{
return false;
}
return true;
}
bool isOperator(string s1)
{
string validOps[4] = { "+", "-", "*", "/" };
for (int i = 0; i < 4; i++)
{
if (s1 == validOps[i])
{
return true;
}
}
return false;
}
double operate(string s1, double d1, double d2)
{
char op = s1[0];
switch (op)
{
case '+':
return d1 + d2;
case '-':
return d1 - d2;
case '*':
return d1 * d2;
case '/':
return d1 / d2;
}
}
bool validString(string str)
{
for (int i = str.size()-1; i >= 0; i--)
{
if (str[i] == '=')
{
return true;
}
}
return false;
}
int processor(string str)
{
TheStack stacklist;
istringstream iss(str);
string streamVar;
iss >> streamVar;
// checks if expression has = sign
if (!validString(str))
{
cout << "Error: Please input valid expression." << endl;
return -1;
}
// builds and operates upon stack
while (streamVar != "=")
{
if (isOperand(streamVar))
{
stacklist.push(stod(streamVar));
}
else if (isOperator(streamVar))
{
if (stacklist.getNodeTracker() > 1)
{
double d2 = stacklist.pop();
double d1 = stacklist.pop();
if (streamVar == "/" && d2 == 0)
{
cout << "Error: Division by 0." << endl;
return -1;
}
double result = operate(streamVar, d1, d2);
stacklist.push(result);
}
else
{
cout << "Error: Too many operators." << endl;
return -1;
}
}
iss >> streamVar;
}
// operand error case
if (stacklist.getNodeTracker() > 1)
{
cout << "Error: Too many operands." << endl;
return -1;
}
// output
cout << stacklist.pop() << endl;
return 0;
}
So I've been working on a project for school for sometime, and I've run up against a wall. My add_node function isn't working correctly, and I know why. What I'm trying to do is take in a file with multiple randomly generated letters, and create trees out of them, then make a confirmation.
The thing is that it overwrites the same node, instead of making multiple nodes. I figured this out using Visual studios debugger, but I have no idea what to implement to fix it. What happens is that instead of having multiple nodes create a tree (like gagtttca), it makes one node and overwrites it. The node becomes g, then a, etc. How would I go about adding more nodes to the tree without overwriting it? The add_node function is the very last one.
#include "stdafx.h"
#include <iostream>
#include <stack>
#include <fstream>
#include <vector>
#include <cstring>
#include <string>
using namespace std;
class myTreeNode
{
public:
char Data;
myTreeNode *childA; //A's always go in child1
myTreeNode *childT; //T's always go in child2
myTreeNode *childC; //c's always go in child3
myTreeNode *childG; //G's always go in child4
};
class Tree
{
public:
myTreeNode * Root;
Tree()
{
Root = new myTreeNode;
Root->Data = '-';
Root->childA = Root->childC = Root->childG = Root->childT = NULL;
}
bool add_a_word(string word);
bool is_this_word_in_the_tree(string word);
bool add_node(myTreeNode * parent, char letter);
bool add_words(vector<string> w);
};
bool get_words_from_the_file(char * my_file_name, vector<string> &vector_of_words);
bool get_the_reads_from_file(char * my_file_name, vector<string> &reads);
bool write_out_the_vector_to_screen(vector<string> my_vector);
bool write_out_the_vector_to_file(vector<string> my_vector, char * my_file_name);
ofstream out;
int main()
{
out.open("my_results.txt");
vector<string> words_in_genome;
char * genome_file_name = "my_genome.txt";//make certain to place this file in the correct folder. Do not change path.
if (!get_words_from_the_file(genome_file_name, words_in_genome))
return 1;
Tree * trees = new Tree();
trees->add_words(words_in_genome);
char * reads_file_name = "reads.txt"; //make certain to place this file in the correct folder. Do not change path.
if (!get_the_reads_from_file(reads_file_name, reads_to_be_tested))
return 1;
for (int i = 0; i < reads_to_be_tested.size(); i++)
{
out <<reads_to_be_tested[i] << " " << trees->is_this_word_in_the_tree(reads_to_be_tested[i]);
}
cout << "All done" << endl;
//Write out a file named "myResults.txt".
//For each read, list its sequence and either "Yes" or "No".
//This will indicate if it does or doesn't map to the genome.
/** Used for debugging
cout << "words" << endl;
write_vector_to_screen(words);
write_vector_to_file(words,"testing.txt");
cout << "reads" << endl;
write_vector_to_screen(reads);
***/
out.close();
}
bool get_words_from_the_file(char * my_file_name, vector<string> &vector_of_words)
{
int i, j;
int len = 0;
ifstream in;
in.open(my_file_name);
if (!in.is_open())
{
cout << "I could not find " << my_file_name << endl;
cout << "Check the location.\n";
return false;
}
char * my_word = new char[11];
while (in.peek() != EOF) { in >> my_word[0]; len++; }
in.clear(); in.close(); in.open(my_file_name);
for (i = 0; i<10; i++)
{
in >> my_word[i];
if (my_word[i]<97) my_word[i] += 32; //makes it lowercase
}
my_word[10] = '\0';
vector_of_words.push_back(my_word);
for (i = 1; i<(len - 10 - 1); i++) //read until the end of the file
{
//shift
for (j = 0; j<9; j++) my_word[j] = my_word[j + 1];
in >> my_word[9];
if (my_word[9]<97) my_word[9] += 32; //makes it lowercase
my_word[10] = '\0';
cout << i << "\t" << my_word << endl; cout.flush();
vector_of_words.push_back(my_word);
}
in.clear(); in.close();
return true;
}
bool get_the_reads_from_file(char * my_file_name, vector<string> &reads)
{
int i;
ifstream in;
in.open(my_file_name);
if (!in.is_open())
{
cout << "The read file " << my_file_name << " could not be opened.\nCheck the location.\n";
return false;
}
char * word = new char[20]; //this is a default, we'll be looking at words of size 10
while (in.peek() != EOF)
{
in.getline(word, 20, '\n');
for (i = 0; i<10; i++) { if (word[i]<97) word[i] += 32; } //makes it lowercase
reads.push_back(word);
}
in.clear(); in.close();
delete word;
return true;
}
bool write_out_the_vector_to_screen(vector<string> my_vector)
{
int i;
for (i = 0; i < my_vector.size(); i++)
{
cout << my_vector[i].c_str() << endl;
}
return true;
}
bool write_out_the_vector_to_file(vector<string> my_vector, char * my_file_name)
{
ofstream out;
out.open(my_file_name);
int i;
for (i = 0; i<my_vector.size(); i++)
out << my_vector[i].c_str()<< endl;
out.clear();
out.close();
return true;
}
bool Tree::add_words(vector<string> w)
{
for (int i = 0; i < w.size(); i++)
add_a_word(w[i]);
return true;
}
bool Tree::add_a_word(string word)
{
myTreeNode * tempNode = new myTreeNode;
tempNode = Root;
if (tempNode == NULL)
{
cout << "The tree is empty" << endl;
}
else
{
while (tempNode != NULL)
{
for (int i = 0; i < word.size(); i++)
{
if (word[i] == 'a')
{
if (tempNode->childA != NULL)
tempNode = tempNode->childA;
else
{
add_node(tempNode, word[i]);//add a node: what letter, who's my parent
tempNode = tempNode->childA;
}
}
else if (word[i]== 'g')
{
if (tempNode->childG != NULL)
tempNode = tempNode->childG;
else
{
add_node(tempNode, word[i]);
tempNode = tempNode->childG;
}
}
else if (word[i] == 'c')
{
if (tempNode->childC != NULL)
tempNode = tempNode->childG;
else
{
add_node(tempNode, word[i]);
tempNode = tempNode->childC;
}
}
else if (word[i] == 't')
{
if (tempNode->childT != NULL)
tempNode = tempNode->childT;
else
{
add_node(tempNode, word[i]);
tempNode = tempNode->childT;
}
}
else
{
cout << "The tree is full, or can't find data" << endl;
return NULL;
break;
}
}
}
}
}
bool Tree::is_this_word_in_the_tree(string word)
{
myTreeNode * tempNode = new myTreeNode;
tempNode = Root;
char com1, com2, com3, com4;
if (tempNode == NULL)
{
cout << "The tree is empty. Sorry" << endl;
}
else
{
while (tempNode != NULL)
{
for (int i = 0; i < word.size(); i++)
{
if (word[i] == 'a')
{
if (tempNode->childA != NULL)
{
if (tempNode->childA)
{
tempNode = tempNode->childA;
com1 = 'y';
}
}
else
{
com1 = 'n';
}
}
if (word[i] == 'g')
{
if (tempNode->childG != NULL)
{
if (tempNode->childG)
{
tempNode = tempNode->childG;
com2 = 'y';
}
}
else
{
com2 = 'n';
}
}
if (word[i] == 't')
{
if (tempNode->childT != NULL)
{
if (tempNode->childT)
{
tempNode = tempNode->childG;
com3 = 'y';
}
}
else
{
com3 = 'n';
}
}
if (word[i] == 'c')
{
if (tempNode->childC != NULL)
{
if (tempNode->childC)
{
tempNode = tempNode->childC;
com4 = 'y';
}
}
else
{
com4 = 'n';
}
}
}
out << com1 << com2 << com3 << com4 << endl;
if (com1 == com2 == com3 == com4)
{
out << "The test passed" << endl;
}
else
{
out << "The test failed" << endl;
return false;
}
}
}
return true;
}
bool Tree::add_node(myTreeNode * parent, char letter)
{
//Can't figure out how to fix error. Run-Time error is that it overwrites the node instead of adding it.
//How would i make it so it's a new node every time?//
myTreeNode * tempNode = new myTreeNode;
tempNode = Root;
tempNode->Data = letter;
tempNode->childA = tempNode->childC = tempNode->childG = tempNode->childT = NULL;
if (tempNode == NULL)
{
cout << "The tree is empty" << endl;
}
else
{
while (tempNode != NULL)
{
if (parent->childA == NULL && letter =='a')
{
parent->childA = tempNode;
}
else if (parent->childC == NULL && letter == 'c')
{
parent->childC = tempNode;
}
else if (parent->childG == NULL && letter == 'g')
{
parent->childG = tempNode;
}
else if (parent->childT == NULL && letter == 't')
{
parent->childT = tempNode;
}
else
{
cout<<"no"<<endl; //for testing//
return false;
break;
}
}
}
return true;
}
Like I stated before, this is a project. I'm not here looking for an easy way out. I just want learn how to fix my code.
The most fundamental problem in your code is the simple obviousness that you're not comfortable using pointers. From the looks of it you may have come from other languages where the vernacular of:
Type *p = new Type;
p = Something;
was common. It is anything-but-common in C++. As in C, dynamic allocation is managed by a returned address, which is saved, cared for, and if all goes well, eventually disposed of. Those addresses are kept in pointer variables. Pointers in C++ don't hold objects; they hold addresses.
That said, I'm not going to destroy everything you wrote. I'm not going to sugar coat this; it would be shooting fish in a barrel. I'm rather going to describe what you should be doing in add_node, show you where you went wrong, and finally proffer up a simple example that eliminates much of the cruft (file io, etc) in your existing code, focusing rather on the real problem at hand: tree node management and the pointer-jockeying that is needed to accomplish it.
The Task
You should be starting at the root node, and for each successive letter in your string, move down the tree. When you encounter a path you want to take, but can't because there is no node hanging there yet, that is when you allocate a new node, hang it, move to it, and continue the process until there are no more characters in your input string.
Your Code
That said, review the comments in the following
bool Tree::add_node(myTreeNode * parent, char letter)
{
myTreeNode * tempNode = new myTreeNode;
// this is outright wrong. you just leaked the memory
// you allocated above. this has no place here and
// should be removed.
//
// Note: the remainder of this analysis will assume you
// have, in fact, removed this line.
tempNode = Root;
// all of this belongs in your myTreeNode constructor.
tempNode->Data = letter;
tempNode->childA = tempNode->childC = tempNode->childG = tempNode->childT = NULL;
// this is flat-out impossible. Assuming you fixed your incorrect
// Root assignment mentioned above, you just allocated a new node
// therefore this can NEVER be NULL (an exception would have thrown
// on a failure to allocate).
if (tempNode == NULL)
{
cout << "The tree is empty" << endl;
}
else
{
// This NEVER changes. Nowhere in the code below this is
// tempNode ever assigned a different value. this loop
// should not even be here. A simple if-else-if stack or
// a switch on letter is all that is needed.
while (tempNode != NULL)
{
if (parent->childA == NULL && letter =='a')
{
parent->childA = tempNode;
}
else if (parent->childC == NULL && letter == 'c')
{
parent->childC = tempNode;
}
else if (parent->childG == NULL && letter == 'g')
{
parent->childG = tempNode;
}
else if (parent->childT == NULL && letter == 't')
{
parent->childT = tempNode;
}
else
{
cout<<"no"<<endl; //for testing//
return false;
break;
}
}
}
return true;
}
Sample Code
The following strips out all the file io, and most of the insanity regarding managing the tree. There are only two member functions, add_word and has_word (the latter used to validate something is indeed present).
What makes this code work is how a pointer-to-pointer is used in the addition and check functions add_word and has_word. For addition, we start at the root node pointer, and with each successive character in the input string, move down the tree. When a child pointer is hit that is NULL, we allocate a new node, hang it, and move on. The check function has_word does exactly the same thing, save for one difference: it doesn't hang new nodes. When it encounters a NULL where there shouldn't be one, it means something is wrong and the input word is not in the tree.
#include <iostream>
#include <random>
#include <string>
struct myTreeNode
{
char data;
myTreeNode *childA;
myTreeNode *childT;
myTreeNode *childC;
myTreeNode *childG;
myTreeNode( char c )
: data(c), childA(), childT(), childC(), childG()
{
}
~myTreeNode()
{
delete childA;
delete childT;
delete childC;
delete childG;
}
// squelch these
myTreeNode(const myTreeNode&) = delete;
myTreeNode& operator=(const myTreeNode&) = delete;
};
class Tree
{
private:
myTreeNode *Root;
public:
Tree() : Root( new myTreeNode('-')) { }
~Tree() { delete Root; }
// squelch these
Tree(const Tree&) = delete;
Tree& operator =(const Tree&) = delete;
// adds a given string into the tree if it isn't already there.
void add_word(const std::string& word)
{
myTreeNode **pp = &Root;
for (auto c : word)
{
c = std::tolower((unsigned int)c);
switch(c)
{
case 'a':
pp = &(*pp)->childA;
break;
case 't':
pp = &(*pp)->childT;
break;
case 'c':
pp = &(*pp)->childC;
break;
case 'g':
pp = &(*pp)->childG;
break;
default:
std::cerr << "skipping unsupported char '" << c << "'\n";
}
if (!*pp)
*pp = new myTreeNode(c);
}
}
// returns true if the given string is in the tree
bool has_word(const std::string& word)
{
myTreeNode **pp = &Root;
for (auto c : word)
{
c = std::tolower((unsigned int)c);
switch(c)
{
case 'a':
pp = &(*pp)->childA;
break;
case 't':
pp = &(*pp)->childT;
break;
case 'c':
pp = &(*pp)->childC;
break;
case 'g':
pp = &(*pp)->childG;
break;
default: // should never happen with proper input
return false;
}
if (!*pp)
return false;
}
return true;
}
};
////////////////////////////////////////////////////////////////////////////////
int main()
{
// setup a random device and some uniform distributions
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<> dchar(0,3);
std::uniform_int_distribution<> dlen(3,8);
// our restricted alphabet. random indexes for creating our
// strings will be coming by indexing with dchar(rng)
char s[] = {'a', 't', 'c', 'g' };
// build set of random strings
std::vector<std::string> strs;
for (int i=0; i<20; ++i)
{
std::string str;
int len = dlen(rng);
for (int j=0; j<len; ++j)
str.push_back(s[dchar(rng)]); // push random char
strs.emplace_back(str);
}
// drop list of strins into tree
Tree tree;
for (auto const& str : strs)
{
std::cout << str << '\n';
tree.add_word(str);
}
// now verify every string we just inserted is in the tree
for (auto const& str : strs)
{
if (!tree.has_word(str))
{
std::cerr << "Word \"" << str << "\" should be in tree, but was NOT\n";
std::exit(EXIT_FAILURE);
}
}
std::cout << "All test words found!!\n";
return EXIT_SUCCESS;
}
Output (varies due to random generators)
gctccgga
agtccatt
gagcg
gtggg
tca
aga
cacaggg
cga
tgga
ttatta
cagg
aac
tatttg
gccttat
acctcca
tgagac
aagacg
tgc
aaccgg
tca
All test words found!!
Summary
I strongly advise you run this in the debugger and step through it with a firm grasp on the watch-window. Follow pointer trails to see how things set up as the program progresses. There are many things I did not talk about: proper construction, initialization, Rule of Three compliance etc. I also could have (and would have had this not been an academic case) used smart pointers such as std::unique_ptr<> or std::shared_ptr<>. I sincerely hope you get something out of this. It's only going to get worse from here.
Best of luck
I don't know why but
this :
Root->childA = Root->childC = Root->childG = Root->childT = NULL;
Doesn't look right for me, haven't done c++ for a while and nodes but i don't think that's how you gotta do it? Will check and edit this.
I have a struct that looks like this:
// A lexical scope that keeps track of every declared variable
// in a function
struct LexState
{
// A map containing the index of a variable in it's function
// The key is the variable name
std::unordered_map<std::string, int> _vars;
Function *_function;
LexState *_parent;
};
This is the code using the struct:
#define DD(msg) std::cout << "Debug: " << msg << '\n'
#define DD1(msg, p1) std::cout << "Debug: " << msg << p1 << '\n'
#define DD2(msg, p1, p2) std::cout << "Debug: " << msg << p1 << p2 << '\n'
// A lexical scope that keeps track of every declared variable
// in a function
struct LexState
{
// A map containing the index of a variable in it's function
// The key is the variable name
std::unordered_map<std::string, int> _vars;
Function *_function;
LexState *_parent;
LexState(LexState *parent, Function *function)
{
_parent = parent;
_function = function;
}
Value *SearchVar(char *name)
{
if (_parent == nullptr)
{
return nullptr;
}
std::string str(name);
auto var = _parent->_vars.find(str);
if (var == _parent->_vars.end())
{
return _parent->SearchVar(name);
}
return _function->GetLocalVar(var->second)->GetValue();
}
};
class Compiler
{
public:
State *_state;
Function *_current_function;
GC *_gc;
LexState *_ls;
Compiler(State *state) :
_state(state)
{
_current_function = nullptr;
_gc = state->GetGC();
_current_function = new Function(nullptr);
_state->_main_function = _current_function;
_ls = nullptr;
}
void PushFunction()
{
Function *new_function = new Function(_current_function);
_current_function = new_function;
LexState *new_ls = new LexState(_ls, new_function);
// even now, right after creating new_ls, new_ls->_vars is 0
printf("%p\n", &new_ls->_vars);
_ls = new_ls;
}
void PopFunction()
{
_current_function = _current_function->_parent;
LexState *parent = _ls->_parent;
delete _ls;
_ls = parent;
}
int DeclareVar(const Symbol *node)
{
assert(node->_type == NODE_SYMBOL);
DD("Declaring variable");
auto token = node->_token;
char name[token->len + 1];
memcpy(name, token->pos, token->len);
name[token->len] = '\0';
int idx = _current_function->AddLocalVar(name);
std::string key(name);
printf("%p\n", &_ls->_vars);
if (_ls != nullptr)
_ls->_vars.insert(std::make_pair(key, idx));
else
DD("LexState nullptr");
DD("Variable declared");
return idx;
}
void Compile(const Node *node)
{
switch (node->_type)
{
case NODE_CHUNK:
CompileChunk((Chunk *)node);
break;
case NODE_BLOCK:
CompileBlock((Block *)node);
break;
case NODE_FUNCTION_DEF:
CompileFunctionDef((FunctionDef *)node);
break;
case NODE_CONDITIONAL:
CompileConditional((ConditionalStatement *)node);
break;
case NODE_BINARY_EXPR:
CompileBinaryExpr((BinaryExpr *)node);
break;
case NODE_UNARY_EXPR:
CompileUnaryExpr((UnaryExpr *)node);
break;
case NODE_SYMBOL:
CompileSymbol((Symbol *)node);
break;
case NODE_STRING_LITERAL:
CompileStringLiteral((StringLiteral *)node);
break;
case NODE_BOOL_LITERAL:
CompileBoolLiteral((BoolLiteral *)node);
break;
case NODE_INT_LITERAL:
CompileIntLiteral((IntLiteral *)node);
break;
}
}
void CompileChunk(const Chunk *chunk)
{
Compile(chunk->_block);
AddCode(OP_HALT);
}
void CompileBlock(const Block *block)
{
std::vector<Node *> vec = block->_vec;
for (auto it = vec.begin(); it != vec.end(); it++)
{
Compile(*it);
}
}
void CompileFunctionDef(const FunctionDef *func)
{
Value v;
int f = AddConstant(v);
AddCode(OP_PUSH, f);
Value *vp = _current_function->GetConstant(f);
if (func->_name)
{
int fvar = DeclareVar((Symbol *)func->_name);
AddCode(OP_STOR_LOCAL, fvar);
}
ArgList *argsnode = (ArgList *)func->_args;
auto args = argsnode->_vec;
int argcount = args.size();
PushFunction();
auto closure = new Closure(_current_function);
closure->_argcount = argcount;
std::cout << argcount << '\n';
vp->_closure = closure;
vp->_type = VALUE_CLOSURE;
// Compiling inside function
// Arguments are compiled in reserved order, because in the function call
// the passed arguments will be pushed in the order they are passed
for (auto it = args.rbegin(); it != args.rend(); it++)
{
int var = DeclareVar((Symbol *)*it);
AddCode(OP_STOR_LOCAL, var);
}
if (func->_guard)
{
Compile(func->_guard);
}
else
{
Compile(func->_body);
}
AddCode(OP_RETURN);
// End function
PopFunction();
}
void CompileConditional(const ConditionalStatement *node)
{
auto function = _current_function;
Compile(node->_condition);
int cond_res_idx = function->AddLocalVar();
AddCode(OP_DUP);
// Store the condition result into an internal variable
AddCode(OP_STOR_LOCAL, cond_res_idx);
AddCode(OP_DUP);
int true_jmp = AddCode(OP_JMP_T, 0);
int false_jmp = AddCode(OP_JMP_F, 0);
// Save index of the first code of the block
int block_idx = function->_code.size();
// Jump to block when condition is true
function->ChangeCode(true_jmp, block_idx);
Compile(node->_expr1);
AddCode(OP_PUSH_LOCAL, cond_res_idx);
// Jump to the end of the whole if-elif-else statement
// if the condition result was true
int exit_jmp = AddCode(OP_JMP_T, 0);
// Save index of the first code after this statement
int right_idx = function->_code.size();
function->ChangeCode(false_jmp, right_idx);
if (node->_expr2 != nullptr)
{
Compile(node->_expr2);
}
else
{
AddCode(OP_PUSH_NIL);
}
int end_idx = function->_code.size();
function->ChangeCode(exit_jmp, end_idx);
}
void CompileBinaryExpr(const BinaryExpr *expr)
{
auto function = _current_function;
auto token = expr->_op->type;
if (token == TOKEN_ASSIGN)
{
if (expr->_left->_type == NODE_SYMBOL)
{
int var = DeclareVar((Symbol *)expr->_left);
Compile(expr->_right);
AddCode(OP_STOR_LOCAL, var);
return;
}
}
// A function call
if (token == TOKEN_LEFTPAREN)
{
ArgList *arglist = (ArgList *)expr->_right;
auto args = arglist->_vec;
int argcount = args.size();
// A function call cannot have more than 255 arguments
assert(argcount < 256);
for (auto it = args.begin(), end = args.end();
it != end; it++)
{
Compile(*it);
}
Compile(expr->_left);
AddCode(OP_CALL, argcount);
return;
}
Compile(expr->_left);
// Both 'and' and 'or' expressions does short circuit
if (token == TOKEN_BOOL_AND ||
token == TOKEN_BOOL_OR)
{
AddCode(OP_DUP);
OpType op = (token == TOKEN_BOOL_AND) ? OP_JMP_F : OP_JMP_T;
int idx = AddCode(op, function->_ip + 1);
Compile(expr->_right);
int next = function->_code.size();
uint32_t instr = function->_code[idx];
function->ChangeCode(idx, next);
return;
}
// No need for lazy evaluation, compile normally
Compile(expr->_right);
switch (expr->_op->type)
{
case TOKEN_ADD:
AddCode(OP_ADD);
break;
case TOKEN_SUB:
AddCode(OP_SUB);
break;
case TOKEN_MUL:
AddCode(OP_MUL);
break;
case TOKEN_DIV:
AddCode(OP_DIV);
break;
case TOKEN_POW:
AddCode(OP_POW);
break;
case TOKEN_AND:
AddCode(OP_AND);
break;
case TOKEN_OR:
AddCode(OP_OR);
break;
case TOKEN_XOR:
AddCode(OP_XOR);
break;
case TOKEN_LT:
AddCode(OP_LT);
break;
case TOKEN_GT:
AddCode(OP_GT);
break;
case TOKEN_LTEQ:
AddCode(OP_LTEQ);
break;
case TOKEN_GTEQ:
AddCode(OP_GTEQ);
break;
case TOKEN_SHIFT_L:
AddCode(OP_SHIFT_L);
break;
case TOKEN_SHIFT_R:
AddCode(OP_SHIFT_R);
break;
}
}
void CompileUnaryExpr(const UnaryExpr *expr)
{
Compile(expr->_right);
switch (expr->_token->type)
{
case TOKEN_SUB:
AddCode(OP_NEGATE);
break;
case TOKEN_NOT:
AddCode(OP_NOT);
break;
case TOKEN_BOOL_NOT:
AddCode(OP_BOOL_NOT);
break;
}
}
// This function gets called only when it's a reference
void CompileSymbol(const Symbol *node)
{
auto token = node->_token;
char name[token->len + 1];
memcpy(name, token->pos, token->len);
name[token->len] = '\0';
DD1("Searching reference: ", name);
Value *upvalue = _ls->SearchVar(name);
if (upvalue)
{
int idx = _current_function->AddUpValue(upvalue);
AddCode(OP_PUSH_UPVALUE, idx);
return;
}
int idx = _current_function->GetLocalVarIndex(name);
AddCode(OP_PUSH_LOCAL, idx);
}
void CompileStringLiteral(const StringLiteral *sl)
{
Value v(sl->_token->str, sl->_token->len);
AddCode(OP_PUSH, AddConstant(v));
}
void CompileBoolLiteral(const BoolLiteral *bl)
{
Value v(bl->_token->type == TOKEN_TRUE);
AddCode(OP_PUSH, AddConstant(v));
}
void CompileIntLiteral(const IntLiteral *il)
{
Value v(il->_token->num);
AddCode(OP_PUSH, AddConstant(v));
}
int AddCode(OpType code)
{
return _current_function->AddCode(code);
}
int AddCode(OpType code, int a)
{
return _current_function->AddCode(code, a);
}
int AddConstant(const Value &v)
{
return _current_function->AddConstant(v);
}
};
The program outputs:
Declaring variable
0
It crashes before the DD("Variable declared") part.
Even though i'm new to C++, I'm pretty sure I don't need to allocate the unordered map myself, right? As it's not a pointer, it will be allocated when I do new LexState
So is there any initialization/allocation I am forgetting?
%i is not the right format specifier to use to print a pointer. You are most likely getting the output that represents a truncated value of the pointer. Use %p instead.
printf("%p\n", &state->_vars);
I don't see anything wrong using state->_vars. See working code at http://ideone.com/YAJK5K.
I have to develop two functions. One is an application level function that merges two sortedlists implemented using dynamic arrays. The other is the same except its supposed to be a member function. I get invalid allocation size. When I trace the function it successfully returns without an error buy as soon as I reach the original calling code I get the error. Here is the code for both functions.
Application level function:
ArraySortedType& merge(const ArraySortedType& list1, const ArraySortedType& list2)
{
ItemType temp;
ArraySortedType ret, list1Copy=list1, list2Copy=list2;
list1Copy.ResetList();
while (list1Copy.GetNextItem(temp) == Success)
ret.InsertItem(temp);
list2Copy.ResetList();
while (list2Copy.GetNextItem(temp) == Success)
ret.InsertItem(temp);
return ret;
}
Member function:
ArraySortedType& ArraySortedType::merge(const ArraySortedType& list)
{
ArraySortedType s, copy = list;
ItemType temp;
copy.ResetList();
while (copy.GetNextItem(temp) == Success)
s.InsertItem(temp);
for (int k = 0; k < length; k++)
s.InsertItem(info[k]);
return s;
}
Code where I call functions:
ArraySortedType u = merge(s, n);
//ArraySortedType k = merge(s, n);
cout << "Length of u is: " << u.LengthIs() << endl;
// cout << "Length of k is: " << k.LengthIs() << endl;
Even the commented out code doesn't work.
Also there is alot of code for implementing the ArraySortedType that I've left out because I think it's unnecessary. Most of it was already given with the lab. InsertItem was implemented by me and is used quite a bit so I'll include it here:
Error_Code ArraySortedType::InsertItem ( ItemType item)
{
if(!length)
{
info[0] = item;
length++;
return Success;
}
for(int i=0;i<=length;i++)
{
if(info[i].ComparedTo(item) != LESS || i==length)
{
for(int j=length;j>i;j--)
info[j] = info[j-1];
info[i]=item;
length++;
return Success;
}
}
return Fail;
}
GetNextItem() and ResetList() were already given so they cant be the problem so I'll leave them out but just tell me if they are required.
I've traced both of them and googled quite a bit but this problem has left me scratching my head. Any help would be appreciated.
EDIT:
I guess the implementation of ArraySortedList will be necessary. Here it is. Guess I don't really expect anyone to actually go through it though:
//ArraySortedType.cpp
#include "ArraySortedType.h"
ArraySortedType::ArraySortedType (int max_items)
{
length =0;
MAX_ITEMS = max_items;
currentPos =-1;
try
{
info = new ItemType[MAX_ITEMS];
}
catch(std::bad_alloc exception)
{
//Severe problem, do not keep program running
cout <<"Memory full "<< endl;
exit(1);
}
}
ArraySortedType::~ArraySortedType()
{
delete [] info;
info = NULL;
}
void ArraySortedType::ResetList ( )
{
currentPos = -1;
}
bool ArraySortedType::IsFull ( ) const
{
if(length == MAX_ITEMS)
{
try
{//Check if memory allocation is fine
ItemType * temp = new ItemType[2*MAX_ITEMS];
delete [] temp;
return false;
}
catch(std::bad_alloc exception)
{
return true;
}
}
return false;
}
bool ArraySortedType::IsEmpty () const {
return (length==0);
}
int ArraySortedType:: LengthIs () const {
return length;
}
Error_Code ArraySortedType::DeleteItem ( ItemType item ) {
int location = 0;
while ((item.ComparedTo(info[location]) != EQUAL ) && location < length)
location++;
if (location == length) return Fail;
info[location] = info[length - 1];
length--;
return Success;
}
Error_Code ArraySortedType::GetNextItem (ItemType& item) {
currentPos++;
if( currentPos == length ) return Fail;
item = info[currentPos] ;
return Success;
}
ArraySortedType::ArraySortedType(const ArraySortedType & ust)
{
MAX_ITEMS =ust.MAX_ITEMS;
length=ust.length;
try
{
info = new ItemType[MAX_ITEMS];
}
catch(std::bad_alloc exception)
{
//Severe problem, do not keep program running
cout <<"Memory full "<< endl;
exit(1);
}
for(int i=0;i<length; i++)
info[i] = ust.info[i];
currentPos=ust.currentPos;
}
ArraySortedType& ArraySortedType::operator=(const ArraySortedType & ust)
{
if(this == &ust) return *this;
if(MAX_ITEMS !=ust.MAX_ITEMS)
{
delete [] info;
MAX_ITEMS = ust.MAX_ITEMS;
try
{
info = new ItemType[MAX_ITEMS];
}
catch(std::bad_alloc exception)
{
//Severe problem, do not keep program running
cout <<"Memory full "<< endl;
exit(1);
}
}
currentPos=ust.currentPos;
length=ust.length;
for(int i=0;i<length; i++)
info[i] = ust.info[i];
return *this;
}
//Assumes that an employee has unique ID
bool ArraySortedType::operator==(const ArraySortedType & ust)
{
if(this == &ust) return true;
if(length!=ust.length) return false;
if(currentPos!=ust.currentPos) return false;
for(int i=0;i<length; i++)
if(info[i].ComparedTo(ust.info[i])!=EQUAL) return false;
return true;
}
Error_Code ArraySortedType::InsertItem ( ItemType item)
{
if(!length)
{
info[0] = item;
length++;
return Success;
}
for(int i=0;i<=length;i++)
{
if(info[i].ComparedTo(item) != LESS || i==length)
{
for(int j=length;j>i;j--)
info[j] = info[j-1];
info[i]=item;
length++;
return Success;
}
}
return Fail;
}
Error_Code ArraySortedType::RetrieveItem (ItemType& item , bool& found)
{
found = false;
int front = 0, back = length - 1, midpoint=(length-1)/2;
while (front<=back)
{
switch (info[midpoint].ComparedTo(item))
{
case EQUAL:
item = info[midpoint];
found = true;
break;
case LESS:
front = midpoint + 1;
break;
case GREATER:
back = midpoint - 1;
break;
}
if (found)
break;
midpoint = ((back - front) / 2 + front);
}
return Fail;
}
Error_Code ArraySortedType::Delete(ItemType startKey, ItemType endKey)
{
bool startFound = false, endFound = false;
int numberDeleted=0, startLocation;
bool deleting = false;
for (int i = 0; i < length; i++)
{
if (info[i].ComparedTo(startKey) == EQUAL)
{
startLocation = i;
deleting = true;
startFound = true;
}
if (deleting)
numberDeleted++;
if (info[i].ComparedTo(endKey) == EQUAL)
{
deleting = false;
endFound = true;
}
}
if (!(startFound || endFound))
return Fail;
length -= numberDeleted;
for (int i = startLocation; i < length; i++)
info[i] = info[i + startLocation];
return Success;
}
ArraySortedType ArraySortedType::RetrieveItemsInRange(ItemType startKey, ItemType endKey)
{
ArraySortedType r;
bool startFound = false, endFound = false;
int numberDeleted = 0, startLocation;
bool retrieving = false;
for (int i = 0; i < length; i++)
{
if (info[i].ComparedTo(startKey) == EQUAL)
{
startLocation = i;
retrieving = true;
startFound = true;
}
if (retrieving)
r.InsertItem(info[i]);
if (info[i].ComparedTo(endKey) == EQUAL)
{
retrieving = false;
endFound = true;
}
}
return r;
}
ArraySortedType& ArraySortedType::merge(const ArraySortedType& list)
{
ArraySortedType s, copy = list;
ItemType temp;
copy.ResetList();
while (copy.GetNextItem(temp) == Success)
s.InsertItem(temp);
for (int k = 0; k < length; k++)
s.InsertItem(info[k]);
return s;
}
ItemType is defined as a class Employee. I really hope I don't have to include it here as well. The class Employee has a compareTo class defined as follows:
RelationType Employee::ComparedTo(const Employee & e)
{
if(eid < e.eid) return LESS;
else if(eid == e.eid) return EQUAL;
else return GREATER;
}
There is a an enum called relation type that has values LESS, EQUAL and GREATER.