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

Ok then Note that :

1234 = 4 * 10^0 + 3 * 10^1 + 2 * 10^2 + 1 * 10^3

And in general suppose a natural number N = a_1a_2....a_n , where a_i is a digit from 0 to 9.

Then we can represent N as follows:
N = a_1...a_n = a_n * 10^0 + a_(n-1) * 10^ 1 ... a_1 * 10^(n-1)

where the "^" means the "power of"

athar89 commented: He knows maths more than i know my girl friend +0
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

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

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

>>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

Do this

queue<state> stateQueue;
state s; 
//initialize s
stateQueue.push( s );
//...blah blah a blah
mrnutty 761 Senior Poster

Don't declare it globally. Your teacher will take points off. Instead do this:

void listmodified(Car car[], int size){
 /* some code here */
}
int main(){
 warehouse car[2];
 /* some code here */
 listmodified(car);
}

so that way you are using the same car thats in main inside of the function listmodified.

mrnutty 761 Senior Poster

Im not talking about the even numbers stored in array,,But im saying that the numbers which are stored on even index of array could be displayed?

Think before you speak. Thats exactly whats he talking about. Fir you need to know
how to generate even numbers such as {0,2,4...}. Then you can use those numbers as indices to your array.

Fbody commented: Thank you :) +3
mrnutty 761 Senior Poster

Ok I see now. Don't be overwhelmed. Before you know it, you will be helping someone out with similar linked list problem.

So lets start :

this function at the end should be private but for testing reason make it public for now :

int LinkedList::getPredecessor(int pos){
};

Now first you want to implement this statement : "If the given position is the first place in the list,the function should return 0."

namely like so :

Node* LinkedList::getPredecessor(int pos){
 if(pos == 0)//we return NULL or 0 since there is no node before the first
   return NULL; 

 //...
};

Now you need to implement this statement :"returns a pointer to the node before that position"

your attempt is close, but this is what you have to do :

Node* LinkedList::getPredecessor(int pos){
 if(pos == 0)//we return NULL or 0 since there is no node before the first
   return NULL; 

  Node* nodeBeforePos = first; 
  for(int i = 0; i < pos - 1; ++i){
      nodeBeforePos = nodeBeforePos->next
  }
  return nodeBeforePos;
};

Lets dissect this new code.

This code : Node* nodeBeforePos = first; declares a Node variable called nodeBeforePos and sets it to point to the first node;
Then this code for(int i = 0; i < pos - 1; ++i) declares a for loop. In which i runs from 0 to pos-1. The reason why its pos-1 is because we want 1 before the pos, therefore we must stop 1 before the pos, …

bmos31 commented: Very clear, walking me through the steps was very helpful +1
mrnutty 761 Senior Poster

>>Rock(enum RockName)
You want :

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

>>5A72 + 4573 = 9FE5

In an algorithmic way, you can do something like this :

string hex1 = "5A72";
string hex2 = "4573"
string res;
assert(hex1.size() == hex2.size());
bool hasCarry = false;
for(size_t n = 0; n < hex1.size(); ++n){
 string hexValues = "0123456789ABCDEF";
 char addedValue = (hex1[n] + hex2[n]);
 if(hasCarry){
   ++addedValue;
   hasCarry = false;
 }
 if(addedValue > 16) { 
    hasCarry = true;
    addedValue %= 16; //map 0-15
 }
 res.push_back(  hexValues[ addedValue ] )
}

The basic idea is to use simple addition algorithm like you would do on paper.
THe above code is not compiled so no guarantee. But it should give you and idea.

But an easy way would be something like so :

int hex1 = 0x5A72;
int hex2 = 0x4573;
int res = hex1 + hex2;
std::cout << std::hex << res << endl;
mrnutty 761 Senior Poster

Its probably because the professor wants the student to learn, instead of blindly using
a function.

Fbody commented: Absolutely! :D +2
mrnutty 761 Senior Poster

>So knowing that, what do you think I should say?

Do you even need to ask? If you want to be with her or just want to be her friend what you need do is EXACTLY the SAME... Yes, that's right. It's exactly the same.

You act and speak to her like nothing happened.

You: Woooohooo looky here, well if it isn't my little side-kick from last summer. How's things?

Her: Hey firstPerson, haha. Yeah I'm good blah blah blah.


If she starts mentioning other guys, you cut her off and say you gotta run.

Like I've always been saying. Act indifferently, do whatever you want to do.

Alright, I am going to try to take your advice. Realize that its not that easy to just forget and act like
nothing happened. She cheated on me. I'm not sure if you ever got cheated on by a girl that you cared for, but
it does not feel good. And I realize that it was her hormones that made her do that, but I'm sure she still has some knowledge
about what she was doing. Anyways, I'm not sure what I'm going to say. But later on, i'm going to message her. And ask her if we
can talk. If everything goes well then good, if not then whatever. I'll let you know what happened tomorrow.

iamthwee commented: Godspeed +0
mrnutty 761 Senior Poster

>>I think vector::reserve() can cause a resize
>>The member functions vector::reserve()... both can cause re-allocation as well

Just to let you know, your first statement is different from your second. reserve does not "resize" the vector as in vector::resize does, so just be weary of the lingo. And as for your second statement, you should point out that, vector::reserve does not affect its element when it tries to change its capacity.

mrnutty 761 Senior Poster

And some food for thoughts,here.

mrnutty 761 Senior Poster

Are you serious? Narue's is gonna kill you lol. Your question is like comparing oranges to apples. Its really useless.

mrnutty 761 Senior Poster

I don't know if my link is appropriate, but what the hell.
I visit my porn site regularly.

mrnutty 761 Senior Poster

This is what you want :

vector<BaseClass*> stuffvector;
BaseClass* temp = new DerivedClass(par_a, par_b);
stuffvector.push_back(temp);
stuffVector.pop_back(); //added, remove all accounts of 'temp'
delete temp;

But I lied, this is what you really wanted :

std::vector< boost::shared_ptr<BaseClass> > baseVec;
baseVec.push_back( new DerivedFromBase() );
//do stuff
baseVec.pop_back();
StuXYZ commented: shared_ptr: Wish more people automatically code with it +3
mrnutty 761 Senior Poster

If you know the input is going to be something like, hour:min:sec then you can just
read it from the stream, and discard the ":" character into a variable or something.

int main(){
	int h(0),m(0),s(0)
	char tmp = 0;	
	cin >> h >> tmp >> m >> tmp >> s;
	cout << h << endl << m << endl << s << endl;
}
mrnutty 761 Senior Poster

Something like this should suffice, although you might want something better :

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

struct SimpleTime{
 int hours;
 int minutes;
 int seconds;
 SimpleTime(int h = 0, int m = 0, int s = 0)
  : hours(h), minutes(m), seconds(s) {}
};

//does no error check
SimpleTime praseStrTime(const std::string& timeStr, char delim ){
 string::size_type hourPos = timeStr.find(delim);
 string::size_type minPos = timeStr.find(delim,hourPos+1);

 string hours = timeStr.substr(0,hourPos);
 string minutes = timeStr.substr(hourPos+1,(minPos - hourPos - 1));
 string seconds = timeStr.substr(minPos+1); 
 stringstream stream( hours + " " + minutes + " " + seconds );
 int timeArray[3] = {0};
 int index = 0; 
 while(stream >> timeArray[index++]) continue;
 return SimpleTime(timeArray[0],timeArray[1],timeArray[2]);
}

void printTime(const SimpleTime& t){
 cout << "hours = " << t.hours << endl;
 cout << "minutes = " << t.minutes << endl;
 cout << "seconds = " << t.seconds << endl;
}
int main(){
 string input = "09:12:59"; //hours:minutes:seconds
 printTime( praseStrTime(input,':') );
 return 0;
}
mrnutty 761 Senior Poster

Do you really need to use the "==" operator. Can you settle for something like this :

typedef pair<int,int> IntPair;
bool hasEqualSecond(const IntPair& lhs, const IntPair& rhs){
  return lhs.second == rhs.second;
}
//....
if(hasEqualSecond(p1,p2)){ /*do something */ }
mrnutty 761 Senior Poster

>>With Linked-list, recursion is your best friend:

I have to disagree, there is no need for recursion here.

mrnutty 761 Senior Poster

Why do you need garbage collection to be a "complete" OOP language?

Because Objects should be able to be created and destroyed by them selves.

Actually in C++ everything is an object.

No not really. A int, float, double, short and any variation of them are not object, they are primitive data types. Functions are not object as well.

main is an object.

I get the feeling that the way you are using the word "object" is in a different sense
than the way object refers to in Object Oriented Programming.

C++ lets people use inheritance to implement run-time polymorphism. And that's
what an object oriented language is.

Is that your definition or is it a standard definition? C++ also makes people go crazy
and insane, but that doesn't mean its a drug?

Why are you capitalizing "Object Oriented", is this some kind of religious thing like you see in the Bible?)

English is not my first language, so whats the correct way of writing Object Oriented?

mrnutty 761 Senior Poster

Memory in C++ fall into 3 category :

static memory : Memory is occupied until the end of the program
heap memory: Memory is occupied until freed
Stack memory : Memory is occupied until the end of the block, in which it was declared.

Thats a very simple description. If you want more details, then maybe you can give us
more detailed question.

mrnutty 761 Senior Poster

Make your getName function a const corrected function like so :

string getName()const; //the const says that it will not change any member variable, presumably

//.cpp
string getName()const{
 return name;
}
mrnutty 761 Senior Poster

>>i want it to end after a character is pressed.

Use this :

vector<int> vec;
int n = 0;
//while user inputs a number, save it
while(cin >> n){ vec.push_back(n); }
 //now reset the stream
 cin.clear();
 cin.ignore(numeric_limits<streamsize>::max(),'\n'); 

 //now carry on with your code
mrnutty 761 Senior Poster

You need to pass the array as you suggested. Its the same as passing an array of ints, or whatever, its just a different type. For example :

int search(Inventory* items, int size){
 /*code to search */
}
void print(Iventory* items, int size){
  /* code to print */
}

So essentially, you need to pass in the inventory.


As for your bonus question, you can use std::vector<Inventory> items;
Google on how to use std::vector.

rObOtcOmpute commented: Nice +1
mrnutty 761 Senior Poster

There is no way in C++, but you can do something like this :

void printN(char c, int n){
	while(n--) cout << c;
}
int main(){
 int a = 1, b = 2;
 const int ADJUSTMENT = 30;
 printN(' ',ADJUSTMENT);
 cout<<a<<" "<<"+ x = "<<b<<endl;
}
mrnutty 761 Senior Poster

>>it[switch statements] doesn't make the slightest difference at the end

On the contrary it does. Switch statements are easier to read, cleaner, and faster
than ifs/else's.


>>But, to be even more on the C++ side, you can use function objects

And to be even more more towards C++ side, you can ditch the new and delete command
for now, and let smart pointers handle it.

mrnutty 761 Senior Poster

@OP: You should do something like this :

int main(){
 Game game;

 while(game.isNotOver()){
  int state = game.getState();
   switch(state){
     case PAUSE_GAME : pauseGame(game); break;
     case PLAY_GAME : playGame(game); break;
     case EXIT_GAME : cleanUp(game); break;
   }
   if(!game.isNotOver){ //if game is over
      bool playAgain =  checkIfUserWantsToPlayAgain();
      if(playAgain) 
         game = Game(); //re-initialize everything
   }
 }
}
jonsca commented: I like it. +4
mrnutty 761 Senior Poster

Ok, first how much of C++ concepts have you learned? In fact, to be more general how much of programming concepts have you learned? Any data structure training? Know
what a pure virtual base class destructor is ? Do you know when is the right
time to use the friend keyword? Do you know anything about how memory works? Or what
type of memory is used in C++? Do you know all the keyword in C++?

Well if your confident enough, then a really good way to get better is to program more. I was in your position a year and 1/2 ago. Finished my programming class. And
I was left with semi knowledge about programming, but because I Love programming, and
I have a passion for it, I went to become a better programmer by doing practice problems, learning the intricate details of C++, and went to program 2d/3d games.

So I recommend to you that you start out doing a lot of practice problems, a lot.
Then after you become comfortable with your language, then go on to incorporate graphics into your projects.

mrnutty 761 Senior Poster

Its undefined behavior because of there is no Sequence_point.

mrnutty 761 Senior Poster

I commented on your actual code. I comment it as I read it.

//Good, gaurds are good, but name them something useful like
// MATRIX_H_
#ifndef GUARD_MM_info
#define GUARD_MM_info

#include "stdafx.h"
#include <vector>
#include <string>
#include <iostream>
#include <utility>
#include <algorithm>

class Matrix {
public:
	//I like this typedef, although I would call it MatrixType.
	typedef std::vector<std::vector<int> > matrix;
	
	//there is really not point to make it const char, just use char
	//also what does calculate do? I cannot tell without looking at its implementation
	//so thats a bad sign already
	int calculate(const char);
	//forget about using reference in primitive types, they make no difference
	//plus a class should have minimal public methods it needs, so to make its job less
	//Thus you should'nt have print and read function in this class, it does not belong there
	void print(const char&);
	void read();
private:
	//Although Its private, at least give it better names so I can understand its job
	void Menu1(); void Menu2();
	void Menu3(); void Menu4();
	void Menu5(); void Menu6();
	//again const ref on primitive types is no point
	int space(const int&);
	void readLeft();
	void readRight();
	//add and subtract probably has very similar code, therefore you can abstract the problem
	//thus less code and easier time for you. 
	void multiply();
	void add();
	void substract();
	std::pair<int, int> setSize(std::string);
	void setValues(const char&, matrix&, const std::pair<int, int>);
	matrix ML;
	matrix MR;
	matrix R;
	int spaces, spaceout;
};
void Matrix::multiply() {
	std::vector<int> v(MR[0].size(), 0);
	R = std::vector<std::vector<int> >(ML.size(), v);

	for(int i = 0; …
mrnutty 761 Senior Poster

>>First_person

Excuse me, I use mixedCaseForMyName, as in firstPerson :)

StuXYZ commented: lol, more code reviews for me. +3
mrnutty 761 Senior Poster

I will be glad to help, first to start out. Here are some guidlines.

1) Get a IDE, I suggest one of these, codeblocks or visual studio 2008.

2) Now you need to start making projects, so google online on how to make projects with either codeblocks or visual studion, whichever you choose to download.

3) Now here is a tutorial in C++. Thats a good start at least. Try some code out. Get it to work and start learning.


We're here to help, so if you have any problems, just ask.

Qu4n7um commented: 100% EPIC ANSWER !! +0
mrnutty 761 Senior Poster

Well thats what a for loop is for. Or you can use strings

string sent = "ILoveYouMary";
string sub = sent.substr(5); //"YouMary"
mrnutty 761 Senior Poster

Ok, I guess the easiest way to do this is to make your own data structure and insert it into a vector and sort it, then copy it back. So first create a struct to hold the elements.

struct Elem{
	int row;
	int col;
	Elem(int r, int c): row(r), col(c){}	
};

then create a compare function for the Elem struct:

bool elemComp(const Elem& lhs, const Elem& rhs){
	if(lhs.row < rhs.row) return true;
	else if(lhs.row > rhs.row) return false;
	//else both row are equal
	//so compare the column
	else if(lhs.col < rhs.col) return true;
	else return false;
}

now this will be your sort function:

void sortIt(int Array[][2], const int rowSize){
 //...
}

Now inside you are going to create a vector of elems like so :

std::vector< Elem > vecArray;

Now copy the array passed in, into the vecArray like so:

for(int i = 0; i < rowSize; ++i){
	vecArray.push_back( Elem(Array[i][0],Array[i][1]) );
}

Now all you got to do is call the std::sort function on it like so:

std::sort(vecArray.begin(),vecArray.end(),elemComp);

Now the vecArray is sorted the way you wanted it to be sorted. All thats left
is to copy it back into the original array like so :

for(int i = 0; i < rowSize; ++i){
	Array[i][0] = vecArray[i].row;
	Array[i][1] = vecArray[i].col;
}

So now the passed in Array is sorted by its x-axis, and secondary to its y-axis.

mrnutty 761 Senior Poster

Instead of making things global, why not make your function take in a _aline as a parameter?
For example ReadConfig(const _aline* line){ /* work with line variable */ }

And all you have to do is make sure that you can call ReadConfig from your file.

StuXYZ commented: I forgot that! +3
mrnutty 761 Senior Poster
Lusiphur commented: Thanks for the reference link :) +1
mrnutty 761 Senior Poster

No I want take one letter and convert that to integer. If that is not possible I have to use array or vector and size would be big.

char n1 = '1';
int num = n1 - '0'; //num equals 1
mrnutty 761 Senior Poster

>>Strings used to be an array of char in C-style coding. Now they're objects in C++.
Forget about what it used to be is C. std::string is a class. An instance of a class
is called an object, so std::string name , here name is an object, because
it is an instance of a class.

>>Does this mean that int and char are not objects?
As pointed out, int and char are primitive data types. The are P.O.D

mrnutty 761 Senior Poster

You should only have 1 main, 1 entry point! I don't know if you have 2 int main() , but if you do, then delete one of them or transfer on of them to the other.

usafsatwide commented: Thanks for all your help +1
mrnutty 761 Senior Poster

Let me try to take a crack at this, after googling it. Its gonna be a long post, so
I hope you are ready to read it.

So first things first you know what inline functions are right? Just to recap, when
you inline a function, you suggest to the compiler that it inline or substitute the
definition where the function call was.

So the next thing, you probably know what virtual function does. Virtual functions
enable polymorphism. When you call a derived class from a base class pointer/ref, it
calls the derived class function.

Ok so thats cleared up. Now lets get started towards the problem.

Here is the first question that needs to be answered, and the main problem
that underlies with inline virtual function, consider the following code :

struct B{
 inline void show(){ _showIt(); } //explicitly tell compiler to hint of inlining it
 void tell(){ _tellIt(); } //implicitly tell the compiler to hint of inlining this func
};

int main(){
 B b;
 b.show();
 b.tell();
}

So suppose a the compiler accepts your inline hint, and inline those function, then
that means b.show() and b.tell() would be substituted with its definition.

Ok now consider this code :

struct B{
 virtual int id(){ return 1; }
};
struct D: B{
 int id(){ return 2; }
};

int main(){
 B base;
 D derv;
 
 base.id();
 derv.id();
}

Now look at the above code. The type of …

StuXYZ commented: Excellent deep answer +3
Nick Evan commented: Good job +15
mrnutty 761 Senior Poster

>>string word2("Over");
>>string word3(3, '!');

The string class, has the proper constructor that allows those syntax. So it calls
the string class constructor. Other that that, i'm not so sure about your question, maybe its because i'm tired.

mrnutty 761 Senior Poster

5.4: inline makes no guarantee on what happens with the function. The compiler decides
what will happen to all function, whether to inline or not.

5.6: No its not possible, although you can always use a struct wrapper.

5.7: what happens there is, when you return num, the compiler makes a copy of num
and stores it in some temporary address, then retrieves it if needed.

mrnutty 761 Senior Poster

whats with the c-style syntax? Use proper C++ syntax here, or else jump towards the C
forum, where your kind are welcomed lol.

string input;
while(cin >> input){
 input[0] = toupper(input[0]);
 cout << input << endl;
}
intills commented: thanks and sorry for not using Proper C++ syntax im new to this cite and to both c and c++, thanks a lot +0
mrnutty 761 Senior Poster

p@arse
thank you drunken master...


firstPerson/Ancient Dragon
so the single quotes are only used for single characters (ONE of the 256)?

yea grasshopper, although its not necessarily limited to 256.

mrnutty 761 Senior Poster

Create a structure :

struct Player{
 string name;
 int score;
 Player() : name(), score(){}
};

Define an extraction operator, to extract into the struct :

std::istream& operator >>(std::istream& inFile, Player& p){
 return inFile >> p.name >> p.score;
}

now create a vector of players :

std::vector<Player> players;

now define a binary boolean function to be used with std::sort.

bool sortByScore(const Player& lhs, const Player& rhs){
 return lhs.score < rhs.score;
}

Now read in from the file into the vector of players :

std::vector<Player> players;
ifstream inFile("filename.txt");
//error check
Player tmp;
 while(inFile >> tmp){ players.push_back(tmp); } //read all from file
 std::sort(players.begin(),players.end(),sortByScore); //sort it
 //now do whatever with the sorted player vector

none of the above is compiled, just an idea to get you started.