mrnutty 761 Senior Poster

The code FLATMATE resident; creates an instance of FLATMATE. It is called an object. Whenever you create a DUTY object, inside that duty object, is an instance of FLATMATE. So each DUTY object has a FLATMATE object. Its similar to this:

class DUTY{
int resident;
}

the only difference is that instead of it being an int, it is of type FLATMATE. You can initialize FLATMATE object in the constructor of DUTY.

mrnutty 761 Senior Poster

For Binary search trees or any data structures that are recursive in nature,
you will want to implement a recursive algorithm to solve most of its problems.Its not only easier to write, but its easier to understand as well. So with that said, consider this recursive algorithm that finds the height of a tree.

int BinaryTree:height(){
 return _height(this.root);
}
int BinaryTree::_height(const Node* root){
  if( isNull( root) ) return 0;
  int leftTreeMax = _height(root.getLeft()) + 1; //add one and move down
  int rightTreeMax = _height(root.getRight()) + 1; //add one and move down
  return std::max(leftTreeMax, rightTreeMax) + 1; //account for the root
}
mrnutty 761 Senior Poster

Yea doesn't look like your destructing it properly. Try something like this :

BinarySearchTree::~BinarySearchTree(){
  _destroy(this._root);
}
void BinarySearchTree::_destroy(Node* root){
  if( isNull(root) ) return;
  else{
     _destroy(root.getLeft());
     _destroy(root.getRight());
      delete root;    
  }
}
Unimportant commented: great solution +1
mrnutty 761 Senior Poster

Should the proper output be 5?

mrnutty 761 Senior Poster

>>Which array-based operations are O(1)?
>>inserting item or deleting item in unsorted array

not quite, what happens if we insert in the middle of the array. How about accessing the data?

>>Which linked-list operations are O(1)?
>>inserting and deleteing item in unsorted lsit
true.

>>Which array-based operations are O(n)?
>>traversing through the list or adding or deleting in a sorted array
its asking you about arrays, why are you mentioning lists?
Whats the difference from "adding" in an array then "inserting" in an array?
In general, inserting and deleting can take up O(n).

>>Which linked-list operations are O(n)?
traversing through the list or adding or deleting in a sorted list
true.

mrnutty 761 Senior Poster

Ok, does the tower of happiness has all the happiness that I need ? Does it include megan fox in there? How about the best food in the world? How about a infinite power machine? So seriously, whats your problem?

mrnutty 761 Senior Poster

Note: bool sayi[10] = {false}; will initialize the whole array to false. So there is no need for sifirla function. Its hard for me to understand your code.

I suggest you do something like the following :

int randRange(int min, int max){
 return rand() % (max-min) + min;
}

//returns a vector with unique random number int range [minValue,maxValue)
//the size parameter declares the size of the vector being returned
std::vector<int> generateUniqueRandom(int minValue, int maxValue, int size){
 assert(minValue >= 0 && maxValue >= 0);
 assert(minValue < maxValue);
 assert(size <= maxValue - minValue ); 
 assert(size >= 0);

 std::vector<int> randomValueList;

 //populate vector with possible random values
 for(int i = minValue; i != maxValue; ++i)
    randomValueList.push_back(minValue);

 //now distort their position randomly
 std::random_shuffle(randomValueList.begin(), randomValueList.end());  

 //now make randomValueList the appropriate size
 int cuttofRange = randomValueList.size() - size;

 randomValueList.erase( randomValueList.begin() + cuttofRange, randomValueList.end() );

 return randomValueList;
}

The code above is not compiled, but it gives you a way to approach it. It might need some tweaking though.

mrnutty 761 Senior Poster

You are not able to create a large array because there isn't enough memory in stack memory. So you have to allocate it and use heap memory like so :

int size = 10e10;
int array = new int[size];

//..utilize array

delete [] array; //release memory for later use

But usually, you might want to do something like this :

std::vector<int> array(10e10,0); //create an array of size 10e10, initialize to 0
mrnutty 761 Senior Poster

Something else to consider :

template<typename T, int ROW, int COLUMN>
class Array2D{
private:
   T _array[ROW][COLUMN];
public:
 Array2D(){/*initialize _array*/}
 //Array2D methods/operations
};

int main(){
 Array2D<int,5,5> array;
}
mrnutty 761 Senior Poster

Your saying this doesn't work :

struct GrowableArray{
 unsigned size;
 double *array;
}
void initialize(GrowableArray& g){
 g.size = 0;
 g.array = 0;
}

What errors do you get? Post some actual code.

mrnutty 761 Senior Poster

Yea, sorry to tell you but std::vector is based on arrays not linked list. It provides those functionalities to be consistent.

mrnutty 761 Senior Poster

>>all the vector class is, is a linked list
Are you implying that a std::vector class is implemented using a linked list data structure?

Example :

template<typename T>
class SpecialList : std::list<T>{
public:
 //add functionalities here
};

Or use composition :

class SpecialList{
 private: std::list<int> listOfInts;
 public: 
  void push_back(int i){ listOfInts.push_back(i); }
  //..more list functions, delegate the job to list;
  //add your functionalities here.
};
mrnutty 761 Senior Poster

>>Data Abstraction: we hide away the implementation details ie we do NOT show how a particular function is implemented

Thats exactly what data encapsulation is.

Data Abstraction means that we factor out common functions from a class and make a separate class thats abstract, so that the other classes can inherit form it.

mrnutty 761 Senior Poster

Data Abstraction means something like this :

//Shape provides no implementation of the draw functions
//It abstracts the draw function from other shapes meaning that it
//defines functions that all type of shapes should necessarily have.
class Shape{
  public: virtual void draw()const=0;
};
class Ellipse : Shape{
 public: void draw()const{ API.drawEllipse(); }
};

Data Encapsulation :

class Info{
 string name;
 int uniqueId;
//....
public:
 string getName(){ return name; }
 int getId(){ return uniqueId; }
};

Notice that we do NOT provide public access for the variables name and uniqueId;
Instead we hide them or encapsulate them, and rather make a function that returns
a copy of them.

mrnutty 761 Senior Poster

easy way out :

void doIt(int start, int end){
  if(start < end){
      printBinaryRepresentation(start);
   }
  else doIt(start+1,end);
}
mrnutty 761 Senior Poster

There is always this :

struct A{
  void methodA(){...};
};
class B{
 A a;
 void methodA(){ a.methodA(); }
}

But thats retarded.

mrnutty 761 Senior Poster

while(! (cin >> theNumber) )
And remove the cin before that line

mrnutty 761 Senior Poster

Its not possible to do what you are doing. The best you can get is :

template<typename T> class CategoricalStats { ... }
template<typename T> struct QualitativeStats{
 typedef CategoricalStats<T> Type;
}
//...
QualitativeStats<float>::Type qstats;

You have that ugly extra level of indirection, but it gets the job done. See here for more details.

mrnutty 761 Senior Poster

use this simple function, :

int getInt(const char *msg){
 cout << msg ;
 int n = 0;
 while(!(cin >> n)){
    cout <<  "Input failed...try again\n";
    cin.clear();
    while(cin.get() != '\n');
 }
 return n;
}

Basically, the while(!(cin>>n)) checks the cin gets what we are expecting it to get. We are expecting it to get an int, so if a letter is entered, cin will fail and set its fail flags. Thus the reason why we did cin.clear(). That clears the flags, and resets the stream. Now all thats left is to discard the invalid input in the stream. To do that, we did while(cin.get() != '\n');. That code discards the invalid character inputted until it reads a newline character.

mrnutty 761 Senior Poster

>>Look up C++ for dummies
HAHAHAHAHA...

We can't inherit constructors, so there is no need for them to be virtual.

Stefano Mtangoo commented: That nails it :) +6
mrnutty 761 Senior Poster

All of this could have been avoid by not using raw pointers. If you can, avoid pointers all together. If not, then use smart pointers.

mrnutty 761 Senior Poster

The problem you suggested should be fixed by modern compilers. Which one are you using?

mrnutty 761 Senior Poster

>>BTW Will this also apply to the file input section

No, once you clear the flags in cin, you do not need to clear it again, unless it fails again.

mrnutty 761 Senior Poster

The problem is with cin. This statement :

while (cin >> x >> y){...}

exits only when cin fails. And when cin fails, you cannot use it until you cleared its flags. Thats why cin >>oname fails.

To solve your problem, do this :

while (cin >> x >> y){
 //...
}
cin.clear(); //clear the flags
while(cin.get() != '\n'); //discard all the bad characters

for(...){...}
cin >> oname
//...and so on with the rest of your code
mrnutty 761 Senior Poster

undefined behavior.

mrnutty 761 Senior Poster

What lines does it crash in?
What is the output before it crashes?
What does the file look like?

mrnutty 761 Senior Poster

Is listNode a even template class? I ask because of this contradiction statements :

listNode<LISTDATA>*

vs

listNode *tempNode = NULL
mrnutty 761 Senior Poster

>>Rock(enum RockName)
You want :

Rock(RockName rockName){ myName = rockName; }
mrnutty 761 Senior Poster

>>why not just find the count directly from the array index

I guess I was thinking in terms of "Design for change" principle. But one reason
I can give you is to save memory. For example the set {a...z} has only 26 characters,
so your array length would be at least of 26 length. So there is some space wasted there if one doesn't use up all the characters. But by using map, its length will be only the number of different characters analyzed.

So with that in mind, I realize that an array of length 26 isn't much these days. But
as I said, I was thinking of design for change, thus if one wanted to count the
frequency of say numbers instead of characters, then its a different ball game.
Because depending on the max number allowed, the array can waste a lot more memory
than map. The same goes for counting frequency for Unicode letters. And what happens if the standard decides to change the "int" value of a character? There could and couldn't be a bug if that happens.

Another reason I can think of is that using arrays, it is more error prone, as one can easily reach out of bounds exception. What happens if the user reads in say a weird value? It could lead to a bug or not. But for its simplicity, and guessing that OP is still learning, its probably an ok …

mrnutty 761 Senior Poster

LOL firstPerson you're at it again.

Stop and engage your grey matter before your EGO flares up and takes over.

I never said using a map was invalid...

Yes YOU would, and YOU would probably be right. But this isn't about you.

Look at the OP's code. Look at his number of posts. Do you think he is advanced to understand your code. This is something a whizz kid would come up with after using c++ for a long time. All your code does is present itself as a cerebral mind numbing exercise for the OP. What do you think his professor is getting the student to achieve here? This task can be achieved simply using just arrays and procedural logic. A student must learn to walk before he can run. Comprende?

Hahaha, I don't speak spanish. Anyways, he did not mention anything about this being a h.w assigned by his professor. For all I know he might be doing this for practice, thus suggesting something better. And I don't think my code was hard to understand, in fact there shouldn't be any troubling understanding it unless one never seen std::map before.

>>I never said using a map was invalid...
Well...."Why should he use a std::map for this?". From that I got, "he shouldn't use map", which is a little variation of "using map here is bad". Maybe just misinterpretation.


Anyways, my code was just a suggestion. OP does not have to follow it. Thats …

mrnutty 761 Senior Poster

Huh? Map is meant to map one data to another. Thus mapping a character to its frequency is perfectly valid and better than using arrays. Its more flexible, safe,robust, and depending on situation would use less memory. I said the code is a little better, because it can be improved but is still better than using raw arrays.

>>Sure a std::map would work but the beauty comes from achieving the same thing with much more rudimentary tools... like classes and arrays

I beg to differ. I would rather use the right tool for the job then try to hack up things using the basic stuff.

mrnutty 761 Senior Poster

If you can you should really use something like std::map for this. For example, doing something like this is a little better:

#include <map>
#include <iostream>
#include <cctype>
#include <fstream>


using namespace std;

class AsciiCharacterCount{
public:
	typedef std::map<char,long>::const_iterator constIterator;	
private:		
	std::map<char,long> asciiFreq;	
public:
	void update(char ch){	 
	 if(isalpha(ch)) asciiFreq[ch]++;
	}
	void update(const std::string& str){
		for(int i = 0; i != str.size(); ++i) update(str[i]);
	}
	long frequency(char ch)const{ 
		 constIterator itr = asciiFreq.find(ch);
		if(itr != asciiFreq.end()) return itr->second;
		else return 0;
	}
	constIterator begin()const{ return asciiFreq.begin(); }
	constIterator end()const{ return asciiFreq.end(); }	
};

int main(){
 AsciiCharacterCount freqCounter;
 freqCounter.update("Alalyze each of these letters");

 AsciiCharacterCount::constIterator itr = freqCounter.begin();
 while(itr != freqCounter.end()){
	 cout << "'" << itr->first << "'" << " frequency = " << itr->second << endl;
	 ++itr;
 }
 return 0;
}
mrnutty 761 Senior Poster

The second one would probably use less memory. And normally you would use the second one unless you have a compelling reason to use the first.

mrnutty 761 Senior Poster

Make your code easier by declaring the function as a boolean function instead of having a found flag. Thus after that change it becomes seemingly simple :

bool MyBS::search(const Node* root, int key){
   if root is null return false;
   else if key < root.key
           search(root.leftChild,key);
   else if key > root.key
           search(root.rightChild,key);
   else return true; //root.key == key   
}
mrnutty 761 Senior Poster

The size of myList is found by using the sizeof() operator. It should be a multiple of 4 bytes.

mrnutty 761 Senior Poster
struct Info{
 string name;
 int age;
 Info(const string& name = "", int age = 0)
  : name(name), age(age){}
};
void add(node* & x, const Info& information)
{
    if( x== NULL ) 
    {
       
        x= new node(information);    
    }
    else if( information> x->data )     {
        add( x->right, information);     
    }
    else  
    {
        add( x->left, information);      
    }
}

//...
//...
myList.add( new Info("james",23) );
myList.add( new Info("charles",32 ) );
mrnutty 761 Senior Poster

@OP: Are you allowed to do this :

struct StudentInfo{
  string name;
  int id;
  //more stuff if you need it

};
struct StudentNode{
 StudentInfo data;
 StudentNode *next;
 StudentNode() : data(), next(NULL){}
 StudentNode( const StudentInfo& info, StudentNode *pNext = NULL)
  : data(info), next( pNext){}
};

class StudentList{
 //...details
public:
 void add(const StudentInfo& info){
    if(start == NULL){
      start= new StudentNode(info,NULL);
    }
    else {
        StudentNode *lastNode = moveToLastNode(start); //returns a Node to the last member
        lastNode->next = StudentNode(info,NULL);
    }
  }
}
mrnutty 761 Senior Poster

I think it maybe due to floating point conversion. Does cap necessarily need to be a double?

mrnutty 761 Senior Poster

Can you post your question a little more clearly with some context?

mrnutty 761 Senior Poster

Oh sorry, this is what I meant.

while(std::cin){
  if(std::cin){
     getnames();
    if(std::cin){ 
       getgrades(); 
     }
  }
}
mrnutty 761 Senior Poster

Do something like this :

while(std::cin){
  if(std::cin){
    getName();
    getGrades();
  }
  
}
mrnutty 761 Senior Poster

Realize that from your code, students and grades might not be the same size. You should instead do something like this:

for each students in the vector students:{
  get student grades.
}
mrnutty 761 Senior Poster

>>test.setValue(value);

test[0].setValue(value);

I'll let someone else criticize your code. Feel too lazy right now.

mrnutty 761 Senior Poster

>>void TimeChild::setTime(miltime)
should be

void TimeChild::setTime(string miltime)

>>void TimeChild::setInt(v)
should be

void TimeChild::setInt(int v)
mrnutty 761 Senior Poster

I think you are looking for reinterpret_cast<>?

mrnutty 761 Senior Poster

>>std::auto_ptr

Thats being deprecated. So I would avoid that. I would rather use boost smart pointers

mrnutty 761 Senior Poster

What you showed above is almost like recursion :

void func(long i){
  if(i > 0)
   func(i - 1);
}

Say "i = 5", then the functin func() will be called 6 times, because of the initial called. So your question is directly related to the question, "whats the highest value of i" assuming no overflow.

The answer to your question is, that it depends. It depends on the memory. You can call a function in another function in another function ...and so on, as long as the memory allows it to. Otherwise there is be a overflow in memory of stack.

mrnutty 761 Senior Poster

Why do you have 2 parameter in your first qAndA function? There is no use of the second parameter.

Here are some links to help you learn more, http://www.gotw.ca/gotw/049.htm, http://www.cprogramming.com/tutorial/template_specialization.html, http://www.parashift.com/c++-faq-lite/templates.html.

mrnutty 761 Senior Poster

Ahh cool. Just one thing then, in the template version using T How does it know what type to return? i would like for float, double, int and char do i give it the type i want like before for that?

Since we can't overload by return types, yes we have to specify the return type like that.

mrnutty 761 Senior Poster

Template specialization like so :

//for general types
template<typename T>
T ask(const std::string& question){
	cout << typeid(T).name() << endl;
	cout << question << endl;
	T answer;
	cin >> answer;
	return answer;
}
//specialize for string type
template<>
std::string ask(const std::string& question){
	cout << "In string\n";
	cout << question << endl;
	cin.ignore(256,'\n');
	std::string answer;
	getline(cin,answer);
	return answer;
}