mrnutty 761 Senior Poster

Just polished it up a little, and fixed a few things. Take a look it will definitely help you to compare your original to this :

#include <iostream>
using namespace std; 



class Calculator{
private: 
	int number1; 
	int number2 ; 
public: 
	Calculator(){
		number1 = number2 = 0;
	}
	Calculator(int input1 , int input2 ){
		number1 = input1; 
		number2 = input2; 
	}

	int addNumber(){
		return number1 + number2;
	}
	int subtractNumber(){
		return number1 - number2;
	}	
	int divideNumber(){
		if(number2 != 0)
			return number1 / number2;
		else return 0; 
	}
	int multiplyNumber(){
		return number1 * number2;
	}

};

int main(){
	
	int numberInput1 = 0; 
	cout << "Enter number 1: "; 
	cin >> numberInput1; 

	int numberInput2 = 0;
	cout << "Enter number 2: "; 
	cin >> numberInput2;


	Calculator t(numberInput1, numberInput2);

	char userOperationChoice; 
	cout << "which operation would you like to perform? ";
	cout << " , enter M for Multiplication, D for Division, A for addition or S for Subtraction:" << endl;


	cin >> userOperationChoice; 	

	switch (userOperationChoice) {

		case 'a' : 					
					cout << "the total is: " << t.addNumber() << endl; 
					break; 

		case 's':
					cout << "the total is: " << t.subtractNumber() << endl; 
					break ; 

		case 'd': 
					cout << "the total is: " << t.divideNumber() << endl; 
					break; 

		case 'm':		
					cout << "the total is: " << t.multiplyNumber() << endl; 
					break; 
	}

	cin.ignore( 256,'\n');
	cin.get();
	return 0 ; 

}
mrnutty 761 Senior Poster

I hope this is a typo :

typedef std::stringstream StreamString;
StringStream& operator<<(StringStream& stream, const TransMatrix& matrix)

I'm not sure whats the problem. Are you sure the errors occurs at line 7?

mrnutty 761 Senior Poster

Whats the error? How is it not working ?

mrnutty 761 Senior Poster

How can i demonstrate that inline functions have internal linkage ?

<quote> Nevertheless, in C++, inline functions are treated by default as having external linkage, meaning that the program behaves as if there is only one copy of the function ( look below for source) </quote>
-------------------------------------------------------------------------------------------
*source

mrnutty 761 Senior Poster

You cant treat your Student class as a POD type because its not. Thus casting it
to char* is wrong. So these calls are a bug:

outfile.write(reinterpret_cast <const char*>(&aStudent), sizeof(Student));
infile.read(reinterpret_cast <char*>(&aStudent2), sizeof(Student));

Use proper insertion/extraction operators which you defined already!

mrnutty 761 Senior Poster

Can you show me real code please? That example is not cutting it. And from your example, your code looks badly designed.

mrnutty 761 Senior Poster

When you remove those objects, as said earlier, the objects destructor should delete
the pointer. But if you are doing something like this :

std::vector<Object*> objVec;
objVec.push_back( new Object() );

then you need to delete the object explicitly :

nt main(){
	std::vector<int*> vec;
	vec.push_back( new int(0) );
	vec.push_back( new int(1) );

	while(!vec.empty()){
		int *p = vec.back();
		delete p; //explicitly delete it
		vec.pop_back();
	}
}
mrnutty 761 Senior Poster

Can you tell me which line it fails at? Is it when you do CAptr->Load()
or is it inside the load function somewhere? I'm guessing it fails inside your load function
for some reason, I cannot say because you haven't provided me with enough code.

mrnutty 761 Senior Poster

Look at each function and think when it cal fail? For example, what happens when you
try to access the top of the list but the list is empty? Is this a case where you
think you should throw an exception? What happens when you try to erase a invalid iterator? Look at each function and think how it would fail. And go from there.

mrnutty 761 Senior Poster

>>
a1x1 + b1x2 + c1x3 = d1
a2x1 + b2x2 + c2x3 = d2
a3x1 + b3x2 + c3x3 = d3

Hint : A good way to solve this is by using linear algebra techniques.

mrnutty 761 Senior Poster

Test to see if "new" is returning a null. That is try this :

ClassA* ptr = new(nothrow) ClassA();
 if(ptr) ptr->Load("test.txt");
 else printError();
mrnutty 761 Senior Poster

After changing it to this :

ClassA* CAptr = new ClassA();
char* p = "test.txt";
CAptr->Load(p);
delete CAptr;

does it still give you a runtime error ?

mrnutty 761 Senior Poster

You should ONLY call delete to the things you call new for.

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 would you want to do that when you can simply use the relational operators :

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

int main(){		
	string s = "100";
	string n = "200";
	
	cout << boolalpha;
	cout << "s == n : " << (s == n) << endl;
	cout << "s <= n : " << (s <= n) << endl;
	cout << "s >= n : " << (s >= n) << endl;
	cout << "s != n : " << (s != n) << endl;
}
mrnutty 761 Senior Poster

I wasn't sure if there was anything performance-loss associated with it, so I just thought I'd ask. As for performance not being something to worry about, actually I do, since I'm setting up some large-scale simulations, and I'm trying now to optimise the inner loop. This belongs to that inner loop.

Thanks for resolving this for me!

Cheers,

Kartik

Thats one of the worst things you can do. You should first write the best code you
can, while making it readable and clear. Then test out the program. If its not fast enough
then you need to use a profiler to find out where the bottleneck is. Then go on from there.
Again, take my advice and don't sacrifice good code with premature optimizations.

mrnutty 761 Senior Poster

>>The only question I have is if this is performance-wise the best solution? Are there solutions that are faster performance-wise?

You don't need to worry about performance at this stage. Your bottleneck is likely to
be somewhere else. I wouldn't see why this is bad. Your not casting things. You are
simply telling the compiler that you don't want to hide the function of the base
class.

mrnutty 761 Senior Poster

>>how would you write this??
points->y; ??

Did you try it?

mrnutty 761 Senior Poster

@OP : You need to do something like this :

template<typename T>
node<T>* copyList(node<T>* front){
 node<T> *newHead = new node<T>(front-value);
 node<T> *curr = newHead;
 for(node<T>* pos = front->next; pos != NULL; pos = pos->next){
    node<T> *tmp = new node<T>(pos->value);
    curr->next = tmp;
    curr = curr->next;
 }

 return newHead;
}

Its not tested so no guarantees.

mrnutty 761 Senior Poster

You want the using declarative :

#include <iostream>

using namespace std;

struct B{
	void p(){ cout << "Base p()\n";}
};
struct D: B{
	using B::p;
	void p(int i){ cout << "Derived p(" << i  << ")\n";}
};

int main(){	
	D d;
	d.p();
	d.p(1);
}
mrnutty 761 Senior Poster

I'm not sure what you are asking for. But Do you want to call Base::computeFunction() inside of Derived::computeFunction()

mrnutty 761 Senior Poster

Your problem is here first :

//iterate through list and copy to newly allocated memory
	while(front->next != NULL)
	{
		//create new node
		temp = new node<T>;
		//set newnode equal to tempHead's next.
		temp = tempHead->next;
	}

First, use the condition while( front != NULL) {...}

Second, your logic is not correct. You need to set tempHead->next equal to temp; Not the other way around.
You also have not initialize temp, to hold the value needed. And you also need to save a copy of the tempHead so you
can return it later.

mrnutty 761 Senior Poster

>>I think the problem got turned into: What is the most weird, convoluted and elaborate way to simply print "Hello World!" 20 times?

Thats how I have fun :)

mrnutty 761 Senior Poster

Instead of while(!sourceFile.eof()) , do this while(getline(sourceFile,extract_line)){ }

Now the extract_line should contain the whole line.

mrnutty 761 Senior Poster

I hope you know that there are libraries already made for this. If you are doing
this just for practice then go ahead.

To get the whole string and not be limited by cin, use getline(cin,stringVariable) . This puts the whole line into the stringVariable. Work from there.

mrnutty 761 Senior Poster

When you print the whole array, output the row sum value. So in your code it would be like this :

for(int i = 0; i != 5; ++i){
	  for(int j = 0; j != 6; ++j){
		  cout.width(10);
		  cout << array[i][j] << " ";
	  }

          cout.width(10);
          cout << colSumRow[i];

	  cout << endl;
  }
mrnutty 761 Senior Poster

It seems as if the more we are technology driven, the more concern we should have of our safety.

mrnutty 761 Senior Poster

Muhahahahahaa

#include <iostream> 
using namespace std;
#define SAY std::cout <<  
#define startProg int main(){ int i = 0;
#define endProg return 0;}
#define FOR(MAX) for(i = 0; i != MAX; ++i){
#define ENDFOR }

startProg
 FOR(20)
	 SAY "hello world\n";
 ENDFOR
endProg
mrnutty 761 Senior Poster

You almost got it, all you had to do was print the result correctly and call the function correctly :

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

void call(int array[][6], const int i){
  int colRowSum[6] = {0};

  //sum to column row
  for(int i = 0; i < 5; i++){
     for( int j = 0; j < 6; j++){
        colRowSum[j] += array[i][j];
      }      
  }

  //print array
  for(int i = 0; i != 5; ++i){
	  for(int j = 0; j != 6; ++j){
		  cout.width(10);
		  cout << array[i][j] << " ";
	  }
	  cout << endl;
  }

  cout << "-----------------------------------";
  cout << "-----------------------------------\n";

  //print result
  for(int n = 0; n != 6; ++n){
	  cout.width(10);
	  cout << colRowSum[n] << " ";
  }

  cout << endl;
}

int main(){
    int array[ 5 ][ 6 ] = { { 100,   567,   434,   100,   269,   324 },
                            { 100,   458,   562,   564,   305,   245 },
                            { 100,   427,   561,   591,   595,   542 },
                            { 100,   536,   491,   204,   502,   253 },
                            { 100,   482,   521,   316,   318,   495 } };

	call (array,5);

	return 0;
 
}
mrnutty 761 Senior Poster

I have to agree, your operator overloading is rather superfluous and rather confusing.
For example you would know what this mean :

Vector3f pos = Vector3f(-1,0,1);
Vector3f view = Vector3f(0,1,1);
float d = pos^view*pos;

But if I was just looking at this code without the full understanding of your
Vector3f interface, then I would be confused, and would have to come and hunt you
down to kill you. Plus do you want the '^' to go first, or did you mean '*' to go first? Of course you might be able to determine by the type of 'd' variable. But imagine if this was a more complicate expression.

For most of Vector operations, I suggest you just write a normal function like so
code like the one below is easy to understand :

Vector3f pos = Vector3f(-1,0,1);
Vector3f view = Vector3f(0,1,1);
float d =  (pos.cross( view )).dot( view );

And lastly, You would definitely make me hunt you down, if I seen your code using
SIMD.

mrnutty 761 Senior Poster

You might be able to do this with smart pointers. But then again, its probably better
to just use glVertex3f(...);

mrnutty 761 Senior Poster

>>adding rows and columns of a multi array

For a second I was happy because I though you were using boost::multi_array, but oh well.

As for a solution to your problem, I suggest you create an array that holds the
sum of each column. Here is some code hints :

void foo(int array[][COL], const int ROW){
  int colRowSum[COL] = {0};

  foreach(row in array){
     foreach( col in array){
        colRowSum[col] += array[row][col]
      }
  }

  printArray2D( array );
  printArray1D( colRowSum );
}
mrnutty 761 Senior Poster

>>. A search will yield a stringstream page, but doesn't give the header name.

What you do then is click on the constructor of the object( in that page ), and it will show you
a full code, using the object at interest.

mrnutty 761 Senior Poster

Well since everyone is posting their solution, might as well post mines :

void printPattern(char ch1, char ch2, const int MAX){	
	for(int r = 0; r != MAX; ++r){
		for(int c = 0; c != MAX; ++c){
			cout << (c % 2 == 0 ? ch1 : ch2 ) ;
		}
		cout << endl;
	}
}
mrnutty 761 Senior Poster

The findNodeBefore should return a reference to the node before the passed in node.
To do that, you need to transverse the node until, node.next equals the passed in node.

mrnutty 761 Senior Poster

When I said, the value of maxPtr, that means *maxPtr . Use the deference operator to get the value of maxPtr.

If you really want to use pointers, then go ahead and do this.

float *current = temps;
const float *end = temps + MAXTEMPS;
float *maxPrt = current, *minPtr = current;

while( current++ != end ){
 if(*current < *minPtr) { /* do stuff */ }
 else if(*current > *maxPtr) { /* do stuff */ }
}

IMO, a while loop looks better than a for loop for these kinds of things.

mrnutty 761 Senior Poster

In your compareNode function you cannot just delete the node like that,

if (curr->nodeValue < target){
 delete curr; //No No No
}

Since this is a single linked list, what you need to do, is set the previous
pointer, that points to curr, to now point to curr.next. Then you can safely delete
curr without messing up the link. Otherwise, you will break the chain. So it should
be something like this :

if(curr->nodeValue < targetValue){
   removeNode(front,curr ); //removeNode fixes the chain, and removes the node from the list
}

void removeNode(node<T>*&front, node<T>*& nodeToRemove){
 node*& prev = findNodeBefore(nodeToRemove, front);
 prev.next = nodeToRemove.next; //fix the link by removing the nodeToRemove node
 delete nodeToRemove;
}
mrnutty 761 Senior Poster

In your last for loop, use an if statement to check if the element in the array is
higher or lower than the current highest and the current lowest. Here is a psuedo-code:

set minPtr to temps;
set maxPtr to temps;

for i = 1 to MAXTEMPS{
 if temps[i] is greater than the value of maxPtr, set maxPtr to temps + i;
 else if temps[i] is lower than the value of minPtr, set minPtr to temps + i;
}
mrnutty 761 Senior Poster

Is the format always going to be like this :

string eq1 = "2A + 3B = 4";
string eq2 = "3A - 2c = 6";

is there any multiplication or division involved? How about parenthesis ?

mrnutty 761 Senior Poster

Ok, thanks for the suggestion.

mrnutty 761 Senior Poster

Its a typical implementation of mergesort algorithm. It runs in a stable time of O(n*log(n) ). Just thought, I would add it to the library. Its been tested, although not very throughly, so if any bugs are found, just post it here, so others can be aware of them.
Its not commented much, if any, because I thought it was self explainable. I realize that
it could have been made more flexible, but I just wasn't interested enough. Happy Coding.

mrnutty 761 Senior Poster

To do stuff like this you need to right tool for the job. C++ is not the correct tool
for this job. I suggest something like php.

mrnutty 761 Senior Poster

Doesn't 3/12 reduce to 1/4 and 9/12 to 3/4.

Also 2/12 reduces to 1/6 not 1/12 (typo I think).

Oops, your completely right. Thanks. Was thinking that, but typed something else.

mrnutty 761 Senior Poster

You are given a number D, for which 0 < D < 1,000,000

Your task : is to find the number of irreducible fractions for a fraction of the
sequence, (D-1)/D , (D-2)/D ... 1/D.

For example, let D = 12; Then listing all fraction increments of 1/D we get :
1/12 , 2/12 , 3/12 , 4/12 , 5/12, 6/12, 7/12, 8/12, 9/12, 10/12, 11/12.

From the list of fractions above, the only fraction not reducible are: 1/12, 3/12, 5/12,
7/12, 9/12, 11/12. While the rest are reducible, for example 2/12 reduces to 1/12, and
10/12 reduces to 5/6.


Problem: Given a denominator D, for which, 0 < D < 1,000,000. Find the number
of irreducible fractions starting from the fraction 1/D to (D-1)/D, while incrementing
the series by 1/D.

mrnutty 761 Senior Poster

It will be easier for you if you read that from a file. If not then you can just do this :

std::vector<string> listOfNum;
listOfNum.push_back( "37107287533902102798797998220837590246510135740250" );
listOfNum.push_back( "46376937677490009712648124896970078050417018260538" );
//...and so on
mrnutty 761 Senior Poster

I think this calls for a do/while loop :

bool driveAnotherCar = false;
do{
  /* drive car code here*/
  char ch = 0;
  cin >> ch;
  if( tolower(ch) == 'y') driveAnotherCar = false;
}while(driveAnotherCar)
mrnutty 761 Senior Poster

How are your list of large number stored? Presumably its stored in a .txt file
in a specific format. Can you give an example ?

mrnutty 761 Senior Poster

>>in C++, there's no reason to distinguish between instances of primitive types and instances of classes that have no public members

Except that they are still different. You are able to add properties to the class if
you choose, where as you can't do that with primitive types. There are still subtle
difference between a instance of primitive versus instance of a class with no interface.


Overall, It seems like what your basically saying is that we can hide the non-object
stuff,and replace them with objects. Thats true we are able to do that. But that
doesn't change the fact that non-object type exist.

P.S :

It really doesn't matter to me what C++ is. All that matters is what I can do with
it. After all, at the end of the day its just a tool like every other language.
The term object oriented, is just something that someone made up, so we can argue
about it in a more sophisticated way. I guess we can just agree to disagree.

mrnutty 761 Senior Poster

You need to first be able to generate prime numbers. When you are able to do that, you
can create some variables to hold the previous and next prime numbers. If their difference is 2, then you got a twin pair. try to code that idea.

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?