C++ :: Class To Store Nodes Of Tree - Converting Between Types
Jun 4, 2013
I'm writing a class to store a tree I have a small issue.
I have a class which stores a node of the tree, something like this:
template<class T>
class node {
private:
(stuff regarding parent node and child nodes);
T __data;
public:
// more stuff (constructors and utility functions) here
};
And I want to I want to be able to do the conversion T(node<T>) implicitly. For example, I want to be able to do this:
node<int> myNode;
myNode=5;
myNode+=10;
myNode*=9;
int x=int(myNode/4);
cout << x+myNode;
And this:
class myClass {
int x;
int y;
void print () {cout << x << ' ' << y << endl;}
Right now I'm working on a TreeView for which I would like to add a TextBlock and a ComboBox as child nodes of a Parent TextBlock node. This would look something like this:
My TreeView is implemented using an MVVM style, and utilizes a HierarchicalDataTemplate. I have had no problems with adding TextBlock nodes and TextBlock children, but the confusion seems to arise when adding child nodes of different UI types.
But then I end up with each node looking like this. It's like each node comes with one TextBlock and a ComboBox (Note: The comboBox is not the child, it and the TextBlock are one node):
How do I allow my treeView to have child nodes of different UI types? I am thinking that my solution has to do with my Hierarchical Data Template.
I am trying to count every node of a binary tree internally (not passing in the root), all my attemps have ended in memory access violation or an inaccurate count (4 or 5) when it should be 10.
This is what I have tried
And yes I am NOT suppose to pass in the root.
int CountChildren() { if ( !Left() && !Right()) return 1; if ( Left() ) return Left()->CountChildren() +1; if ( Right() ) return Right()->CountChildren() +1; }
I'm trying to count the number of node in a binary tree. I have a public count function that calls a private count function. I keep getting a linker error: Undefined symbols for architecture x86_64:
"BST<int>::nodesCount(BST_Node<int>*, int&)", referenced from: BST<int>::nodesCount() in main.o
This is in Xcode. It doesn't seem to like calling the private function in the public one, but I'm not sure why since I'm doing that with several other functions.
//public function template <typename T> int BST<T>::nodesCount() {
In class we were asked to create a C++ BTree program that would allow a user to input the following data types and then store said data in a .txt file:
0. ID 8 bytes
1. First name 30 char
2. Last Name 30 char
3. Street Address one 30 char
4. Street Adress two 30 char
5. City 30 char
6. State 20 char
7. Zip 10 char
8. Country 30 char
(I'm not particularly asking for full code, pseudo code would also be great). I had a great deal of my work done, unfortunately, the computer I was working on crashed, corrupting my files.
I was working on float and double data types and to see the results i wrote this program:
#include <iostream> #include <iomanip> #include <fstream> using namespace std; int main() { ofstream outputF("output.txt"); double a = 1; double outcome;
[Code] ....
Well I understand the part it cannot store infinite numbers. but if you take a look at the output for example (since it is too long i just added some of the outputs)
//--------------------- for the value of : 001 1 //--------------------- for the value of : 002 0.5 //--------------------- for the value of : 003 0.3333333333333333148
[Code] ....
if you look carefully at the value "5" and "10" results. it is awkwardly abnormal. which is something i couldnt understand. also it is the same with value "20", "25", "40", "50" and so on.
Suppose your program has many concrete subtypes of Person, and each person will have their own file saved, with their type stored in that file. When reading the files to create the people again (of their proper types), what is the best method to maximize performance (and elegance by shortening the code)? Here is what I have so far.
First I used if statements, which is terrible, and now I've improved the performance logarithmically using std::map. I still suspect there is a better way, especially if there are going to be hundreds of different classes. If you want to test it, you can change the PATH constant to whatever path you want, or just leave it as an empty string, and the files will be created in the same directory as your cpp file. The part I'm trying to improve is pointed out in the comments.
struct Person { std::string name; Person (const std::string& newName) : name (newName) {} virtual ~Person() = default; }; struct Guy : Person {using Person::Person;}; struct Girl : Person {using Person::Person;};
Error1error C2440: 'initializing' : cannot convert from 'const char [4]' to 'Course' Error2error C2440: 'initializing' : cannot convert from 'int' to 'Course'158 Error3error C2440: 'initializing' : cannot convert from 'const char [6]' to 'Course'158 Error4error C2078: too many initializers158
# include <iostream> # include <cstring> #include <iomanip> #include <cmath> using namespace std; class Course { public: char CourseName[10]; // Array of size 10, 9 characters and 1 null terminator
[Code] .....
And in the /// part I also need to use the dot operator and the arrow operator to print on the screen info about the second and third Courses.
I have been thinking about this all day and I am yet to come up with a good solution. So, I need to design an image class which should work with various data types (int, float, double etc.) and can also be multidimensional (2, 3, 4, 5). So, what I did was generate a template image class as follows:
Code: template<typename T, int dimensions=3> class Image { private: T * data; };
Anyway, now I have various image formats that I want to support, so the easy thing to do is create a Factory sort of object which will call eventually generate the correct image.
So I want to create various image classes called ImageType1, ImageType2 etc. which will take the input image and generate the correct Image object. However, I do not want these objects to be templated because they need to be passed from functions and be used in a generic way.
So, at run time I will need to be able to do this…
Code: class ImageType { public: ImageType() { PolymorphicImage * image = new Image<float, 3>(); } private: PolymorphicImage * image; };
So, I want my ImageType classes to contain the Image object and be able to generate it with the right template arguments at run time. Is there any way to do this without having multiple specialised definitions for ImageType?
int check_up(char string[]); int check_low(char string[]); void to_up(char string[]); void to_low(char string[]);
[Code] .....
When I compile this I have the following problems: warning: data definition has no type or storage class [enabled by default] in 'to_up(word)'conflicting types in 'to_up' function and to_low function warning: data definition has no type or storage class [enabled by default] into_up function error: unknown type name "word" in line 'printf("All uppercase %s. ", word):;'warning: parameter names (without types) in function declaration [enabled by default] in 'to_up(word)'and 'to_low(word)' 'note: previous declaration of "to_up" was here in function declaration of to_up function
Sandy is of class Person, who converts to Muslim and takes on a new name Fatima, and has all the attributes of Sandy, with new Muslim attributes (e.g. religion == Islam, etc..). At this point, Sandy can be deleted, and Fatima, now of class Muslim will play Sandy's role henceforth. The problem is that due to her new address, all the people who knew Sandy does not know Fatima. Manually changing Sandy's address to Fatima's address for all those people who knew Sandy is clearly not an acceptable method. I looked through all the design patterns and cannot find one to solve this problem. how to improve the design? Here's my simplified code showing the problem:
#include <iostream> #include <string> #include <typeinfo> class Person { std::string name; Person* bestFriend;
[Code]...
Output:
sandy = 0x32658, 6Person Mary's best friend is Sandy. fatima = 0x23fec0, 6Muslim Mary's best friend is Sandy.
Of course, we want to have: Mary's best friend is Fatima,. with mary->getBestFriend()->getReligion() == Islam, etc... How to redesign the whole thing so that this is automated (assume there are thousands of people who know her)?
Creating array in main and then calling a sorting function from sorting class.
In main:
const size_t SIZE = 100; int *array = new int [SIZE]; //fill array with ints, not shown here quickSort(array, SIZE); //calling the sorting function in the sorting class
In the sorting class, quickSort is declared as such:
void quickSort(int arr[], int num);
Everything works great.
Version 2 (issues)
Instead of creating the array in main, I have set up a class for the array, MyArrayClass, where I create an object containing the array of ints. So far so good. The issues come when I write a member function to call quickSort. Even though my MyArrayClass object contains an array of ints, the code calling for quickSort() won't compile as the data type isn't ints but MyArrayClass (which in turn holds ints though). The compiler (using VS 2013 btw) complains that quickSort can’t convert the first argument from 'const MyArrayClass' to 'int[]'.
How do I cast my class object array of ints as an int[] in order to be able to call the quickSort function? Or should I solve this issue in some other way? I tried altering the sorting function to accept the object as it is, but that only created an avalanche of new errors, so thinking that converting/casting the object array --> int[] might be easier...
I'm trying to implement a binary tree using this class:
class btree { public: int key; btree *left; btree *right; btree(){left=NULL; right=NULL;} void insert(int key);
[Code] ....
gives me the following error:
albero_binario1.cpp: In member function ‘void btree::insert(int)’: albero_binario1.cpp:34:18: error: lvalue required as left operand of assignment albero_binario1.cpp:39:15: error: request for member ‘insert’ in ‘((btree*)this)->btree::right’, which is of non-class type ‘btree*’ albero_binario1.cpp:41:14: error: request for member ‘insert’ in ‘((btree*)this)->btree::left’, which is of non-class type ‘btree*’
I am trying to write a Fraction class and getting the following warning when compiling my code :
Fraction.cpp: In constructor 'Fraction::Fraction(double)': Fraction.cpp:8: warning :converting to 'int' from 'double'
My Fraction.cpp class looks like :
#include "Fraction.h" Fraction::Fraction(int n, int d):num(n),den(d) { cout << This is double param constructor <<endl; } Fraction::Fraction(double d):num(d),den(0)
I'm trying to implement a decision tree that gets doubles as input (in this sample code just random numbers) and returns a boolean value. At the nodes, I'd like to use various operators that can have different input and return types. I've implemented an abstract base class for the nodes and I'm deriving the specific nodes from it. In the code below, I've included only a few derived classes. Building the tree (randomly) is no problem. However, I'm looking for a clever way to evaluate the tree. I think that uncommenting the lines in bold print would in principle do it. However, this is not possible because "value" is not a member of the base class. The type of "value" is different in the derived classes, so I cannot simply declare it in the base class.
"Node.h" #pragma once class NodeBase{ public: NodeBase* Child_1; NodeBase* Child_2; virtual void evaluate() = 0;
I am working on a program that uses a class I created called Student. I want to be able to add different students to a Binary Search Tree, and use the student's gpa (grade point average) to compare students with each other and place them in the correct location in the Tree.
I have a class I use to store column data read from delimited text files.
Code: class column_data { // class functions here public: // initialize class members column_data() : header(""),
[Code] ....
Each column is read into the vector of string. Next the string data is copy converted to the vector of double or the vector of int depending on the data type. There can also be additional transformations of the data (normalization, scaling, etc) and the transformed data is copied to the transformed_double_data vector. I do end up with multiple copies of the data, but I can clear some of the vectors if I don't need all the versions of the data anymore. Each column object goes into a container like a vector of objects or map of objects depending on how I need to access the column data.
There are functions that calculate statistics on the data in the columns and the results are assigned to the object variables like validate_r2. There are separate statistics for each column, so it seems logical to store the results in the column object. This works well for statistics like validate_r2 (pearson's correlation coefficient).
The current issue is that I have other statistics like "pw50" that I need to calculate and store. The statistic is the percent within +/- 50 units and the request for pw50 is passed in from the command line. The issue is that there could be several of these and they can have more or less any value like, pw50, pw75, pw100, etc. Storing data like this doesn't fit into my scheme very well because I can't pre-declare a variable to hold the result for every possible option. I don't know in advance how many, if any, of these there will be. I was thinking of adding two vectors, one of string and one of double,
Code: class column_data { public: // initialize class members column_data() : header(""), type(""), use(""), validate_r2(0.0),
[Code] ....
For each of this type of statistic requested, I would push_back a label into the string vector and then put the result into the parallel position in the double vector. This seems like I would work, but there are probably some things that could be done with pointers that might be better. Another option would be a vector of objects where each object had a string value for the label and a double for the result. That would be more bullet proof as far as keeping the label and value together, but I have not ever nested objects in a class like that so I thought I would post. I don't know the syntax for declaring an object of class_b inside the definition of class_a. The need is to provide dynamic storage for an unspecified number of these statistics and a reliable way to retrieve the values using the label.
Assignment: Design a class to store measurements. The class should have two data items, feet and inches, both integers. The class must make sure that the number of inches never gets below zero or above 11. If inches is outside that range, adjust feet accordingly. (Yes this means feet might be a negative number.)
Create a default constructor and one which receives one integer, a number of inches.
Overload the following operators: addition, subtraction, equality, inequality, incrementation (both pre and post) (should add one to inches), and output (in the form of: F’I”)
Code: #include <iostream> using namespace std; class measurements {
private: int inches; double feet;
[Code] ....
I am getting a LNK2019 error and an LNK1120 errors:
Error 1 error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup