I'm trying to write simple binary tree program in C++ using VS 2012.Even all paths are set it give me link error as shown in attached and when i comment the comment-out inside the insert function, it compiles without error.
// C++ code
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout <<" Simple Binary Tree Examples";
getchar();
return 0;
}
struct node
{
int data;
node *left;
node *right;
};
public class BinaryTree
{
public :
BinaryTree();
~BinaryTree();
void insert(int value);
/*{
if(root==NULL)
{
insert(value,root);
}
else
{
root = new node;
root->data=value;
}
}*/
void delete_tree();
private:
node *root;
void insert(int value,node *leaf);
};
BinaryTree::BinaryTree()
{
root=NULL;
}
BinaryTree::~BinaryTree()
{
delete_tree();
}
void BinaryTree::insert(int value)
{
// If i un-comment the below code.. it gives link error.
/* if(root==NULL)
{
insert(value,root);
}
else
{
root = new node;
root->data=value;
}*/
}
really dont know what could be wrong and hence shared the entire code.
Your code doesn't contain a definition of delete_tree, which is mentioned in your destructor.
It shouldn't compile neither with that code commented, nor with it.
Related
This problem occurs in my main.cpp:
using namespace std;
#include <iostream>
#include "BST.h"
#include "Packet.h"
int main()
{
BST test; // It occurs on this line!
Packet one(1, "testPacket", 1, 1);
system("Pause");
}
The error on that line says:
argument list for class template "BST" is missing
I don't know how to fix it. I just want to initialize the BST. How can I fix this error? I'm not very experienced with templates. Please help. My priority is fixing this glaring problem right now. Can I get help?
For reference purposes:
BST.h:
#ifndef BST_H
#define BST_H
using namespace std;
template <typename T>
class Node {
public:
Node() : rlink(nullptr), llink(nullptr) {}
~Node() {}
private:
T data;
Node *rlink, *llink;
};
template <typename T>
class BST {
public:
BST();
void insert(T data);
private:
Node * root;
};
#endif
BST.cpp
#include "BST.h"
template <typename T>
BST<T>::BST() : root(nullptr) {}
template <typename T>
void BST<T>::insert(T data) {
if (root != nullptr) {
}
else {
cout << "NPTR" << endl;
}
}
Packet.h
#ifndef PACKET_H
#define PACKET_H
#include <string>
using namespace std;
class Packet {
public:
Packet(int partId, string description, double price, int partCount) :
partId(partId), description(description), price(price), partCount(partCount) {}
int getPartId() const { return partId; }
string getDescription() const { return description; }
double getPrice() const { return price; }
int getPartCount() const { return partCount; }
private:
int partId;
string description;
double price;
int partCount;
};
#endif
There are 2 problems.
The first is that Node needs to know what type T is, so you need to tell it when you use Node like this:
template <typename T>
class BST {
public:
BST();
void insert(T data);
private:
Node<T> * root;
};
Secondly, BST needs to know what its own type T is when you try to use it, so you need to do it like this:
BST<int> test; // Or whatever you are searching for in your tree. Doesn't have to be an int
P.S. Just heading this off now, you're probably going to need to implement BST in the header file. Failure to do so might cause linker problems.
P.P.S. I've been reading your comments on the original post, and what you actually probably need this instead:
BST<Packet> test; // Since you are searching for packets.
I am trying to get this to return a string, but i am having trouble getting it working. The goal is to have a doubly-linked list that points to strings. I am not allowed to have it contain the string, it must point to it instead. Currently i am having trouble getting my program to use it. For example, it always seems to return what the command was, and its confusing me and hard to explain.
#ifndef DOUBLY_LINKED_LIST_H
#define DOUBLY_LINKED_LIST_H
#include <iostream>
#include <string>
//#include "Playlist.h"
using namespace std;
class DoublyLinkedList
{
public:
DoublyLinkedList();
~DoublyLinkedList();
bool empty();
void append(string& s);
void insertBefore(string& s);
void insertAfter(string& s);
void remove(string& s);
void begin();
void end();
bool next();
bool prev();
bool find(string& s);
const string& getData();
private:
class Node
{
public:
Node (string *data, Node *next, Node *prev)
{m_data = data; m_next = next; m_prev = prev;}
string *m_data;
Node * m_next;
Node * m_prev;
};
Node *m_head;
Node *m_tail;
Node *m_current;
};
#endif // DOUBLYLINKEDLIST_H_INCLUDED
.cpp file>>>>
const string& DoublyLinkedList::getData()
{
string *m_tmp;
m_tmp = m_current->m_data;
cout << m_current->m_data << endl;
//cout << "returning: " << m_current->m_data << endl;
// return m_current->m_data;
return *m_tmp;
}
void DoublyLinkedList::append(string &s)
{
if (!m_head)
{
m_head = new Node(&s, NULL, NULL);
m_tail = m_head;
m_current = m_head;
}
else
{
m_tail->m_next = new Node (&s, NULL, m_tail);
m_tail = m_tail->m_next;
m_current = m_tail;
}
}
Consider the following example:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void store_value(vector<string*>& vec, string& str)
{
vec.push_back(&str);
}
void create_and_store_value(vector<string*>& vec)
{
string str("This string is temporary");
store_value(vec, str);
}
int main(int argc, char** argv)
{
vector<string*> pointers;
create_and_store_value(pointers);
cout << *pointers.back() << endl;
string myPersistingString("Yay");
store_value(pointers, myPersistingString);
cout << *pointers.back() << endl;
return 0;
}
This example contains two function, a function store_value which behaves similar to your append function (except, for the purposes of this example working on a std::vector) and a second function showing the possible danger of taking the address of a reference (this is one of the possible hazards that I believe Manu343726 and Mats Petersson are preluding too).
The reason this is dangerous is because the string declared inside create_and_store_value does not persist after the completion of the function. This means that we are left with a pointer to memory which is probably not what we expect. On the other hand, creating a string inside the main function is fine, since the string there persists until the end of the program.
For us to help you further, I would suggest editing your question to give us an example of how you are calling your function. I would suggest pasting a minimal striped down version of your code including an example of how you are calling append, something like:
#include <blah>
class DoubleLinkedList
{
DoubleLinkedList(void)
{
// Include these inline to make copying and pasting simpler.
}
~DoubleLinkedList(void)
{
...
}
append(...) { ... }
getData(...) { ... }
};
int main(int argc, char** argv)
{
DoubleLinkedList dll;
// Show us how you are using this list
return 0;
}
In the above, replace the comments and dots with the relevant code.
I feel this question may be a bit trivial, but I simply cannot wrap my head around it. I currently have a class, Node, which is trying to point to what node occurs before the current node using the pointer prevNode. However I seem unable to access any variables within prevNode.
When running Main.cpp from the following code, it prints the result '15340756'. Where am I going wrong? Appologies as Im still a bit new to C++.
Node.h
#include "stdafx.h"
class Node
{
public:
Node();
void setPrevNode(Node n);
Node getPrevNode();
int i;
private:
Node *prevNode;
};
Node.cpp
#include "stdafx.h"
#include "Node.h"
Node::Node(){
i = 0;
}
void Node::setPrevNode(Node n){
prevNode = &n;
}
Node Node::getPrevNode(){
return *prevNode;
}
Main.cpp
#include "stdafx.h"
#include "Node.h"
int _tmain(int argc, _TCHAR* argv[])
{
Node nodes[] = {Node(), Node()};
nodes[0].i = 1;
nodes[1].setPrevNode(nodes[0]);
printf("%i", nodes[1].getPrevNode().i);
while(true){
}
return 0;
}
void setPrevNode(Node n);
Here setPrevNode is declared to take a copy of the node passed as an argument, and point to such node. After the function returns, the pointed to node no longer exist and what you get is undefined behavior.
What you want is to take the Node either as a reference or a pointer instead:
void setPrevNode(Node& n)
{
prevNode = &n;
}
void setPrevNode(Node* n)
{
prevNode = n;
}
On the same line, getPrevNode is defined to return a copy of the previous node. You most certainly want to return a reference here instead, although you can also return a pointer:
Node& getPrevNode()
{
return *prevNode;
}
Node* getPrevNode()
{
return prevNode;
}
I keep getting this error message every time I try to compile, and I cannot find out what the problem is. any help would be greatly appreciated:
C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::List()'
C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::add(int)'
collect2: ld returned 1 exit status
code:
//List.h
#ifndef LIST_H
#define LIST_H
#include <exception>
//brief Definition of linked list class
class List
{
public:
/**
\brief Exception for operating on empty list
*/
class Empty : public std::exception
{
public:
virtual const char* what() const throw();
};
/**
\brief Exception for invalid operations other than operating on an empty list
*/
class InvalidOperation : public std::exception
{
public:
virtual const char* what() const throw();
};
/**
\brief Node within List
*/
class Node
{
public:
/** data element stored in this node */
int element;
/** next node in list */
Node* next;
/** previous node in list */
Node* previous;
Node (int element);
~Node();
void print() const;
void printDebug() const;
};
List();
~List();
void add(int element);
void remove(int element);
int first()const;
int last()const;
int removeFirst();
int removeLast();
bool isEmpty()const;
int size()const;
void printForward() const;
void printReverse() const;
void printDebug() const;
/**
enables extra output for debugging purposes
*/
static bool traceOn;
private:
/** head of list */
Node* head;
/** tail of list */
Node* tail;
/** count of number of nodes */
int count;
};
#endif
//List.cpp I only included the parts of List.cpp that might be the issue
#include "List.h"
#include <iostream>
#include <iomanip>
using namespace std;
List::List()
{
//List::size = NULL;
head = NULL;
tail = NULL;
}
List::~List()
{
Node* current;
while(head != NULL)
{
current = head-> next;
delete current->previous;
if (current->next!=NULL)
{
head = current;
}
else
{
delete current;
}
}
}
void List::add(int element)
{
Node* newNode;
Node* current;
newNode->element = element;
if(newNode->element > head->element)
{
current = head->next;
}
else
{
head->previous = newNode;
newNode->next = head;
newNode->previous = NULL;
return;
}
while(newNode->element > current->element)
{
current = current->next;
}
if(newNode->element <= current->element)
{
newNode->previous = current->previous;
newNode->next = current;
}
}
//main.cpp
#include "List.h"
#include <iostream>
#include <string>
using namespace std;
//void add(int element);
int main (char** argv, int argc)
{
List* MyList = new List();
bool quit = false;
string value;
int element;
while(quit==false)
{
cin>>value;
if(value == "add")
{
cin>>element;
MyList->add(element);
}
if(value=="quit")
{
quit = true;
}
}
return 0;
}
I'm doing everything I think I'm suppose to be doing. main.cpp isn't complete yet, just trying to get the add function to work first. Any help will be greatly appreciated.
Describe your build process. It looks as though you're not building List.cpp, or else not linking it with main.cpp.
You're not compiling List.cpp. Add it to the command line.
In main.cpp, it's seeing (from List.h) "Hey, this class with this functionality will exist", but since you're not actually building/linking with List.cpp, it can't find the functions it's looking for.
Your command line should look something like g++ -o test.exe main.cpp List.cpp.
The key feature being to include both main.cpp and List.cpp.
There are other ways to do this, but this should get you started.
Your problem is not including all the different files in your command line arg compiler
Correct format:
get in correct directory
gcc -o list main.cpp List.cpp List.h
then you won't get anymore undefined references to functions
Good luck on building your 3 or 4 year old program...
I'm trying to implement a linked list but get an error when compiling:
intSLLst.cpp:38: error: ‘intSLList’ has not been declared
intSLList looks like it's been declared to me though so I'm really confused.
intSLLst.cpp
#include <iostream>
#include "intSLLst.h"
int intSLList::deleteFromHead(){
}
int main(){
}
intSLLst.h
#ifndef INT_LINKED_LIST
#define INT_LINKED_LIST
#include <cstddef>
class IntSLLNode{
int info;
IntSLLNode *next;
IntSLLNode(int el, IntSLLNode *ptr = NULL){
info = el; next = ptr;
}
};
class IntSLList{
public:
IntSLList(){
head = tail = NULL;
}
~IntSLList();
int isEmpty();
bool isInList(int) const;
void addToHead(int);
void addToTail(int);
int deleteFromHead();
int deleteFromTail();
void deleteNode(int);
private:
IntSLLNode *head, *tail;
};
#endif
You're using a lower case i
int intSLList::deleteFromHead(){
}
should be
int IntSLList::deleteFromHead(){
}
Names in c++ are always case sensitive.
intSLList isn't the same as IntSLList. This isn't Pascal. C++ is case sensitive.