mrnutty 761 Senior Poster

So you want something like this then.

#include <iostream>
#include <string>

using namespace std;

typedef string (&ErrorFunc)();

string myError(){ return "Failure"; }

void logFile(const std::string& id,const ErrorFunc func){
  cout << id << func() << endl;
  //log into file
}

int main(){
 logFile("Msg : ", myError );
}
mrnutty 761 Senior Poster

So in the above example, you want the message generated by myeql_error() to be logged into the file? I am assuming mysql_error() returns a string or something similar?

mrnutty 761 Senior Poster

@OP: Usually you should avoid the usage of static keyword. To further explain the problem consider what happens here :

int x = 10;
int &y = x;
y = 20; //x = 20 as well

Since y is a reference to x. Changing y will also change x. Basically, y is another name for x.

Now what happens when x is not valid, meaning when it goes out of scope? For example
this function shows such a case:

int& getFive(){
 int x = 5;
 return x;
}

and call it like so int& y = getFive(); . Now just like in the other y is a reference to x. But this time x is not valid. x is not valid because it goes out of scope and the compiler destroys it. Here is a psuedo-sequence of what happens in the above call to getFive();
1) y is declared as a reference to getFive();
2) getFive() gets executed
3) Inside getFive() the variable x gets created and initialized to 5. Since x is not declared static, you tell the compiler that it goes out of scope at the end of the function and thus should get destroyed and free the memory it occupies.
4) Now you try to return x. But the function says that return x as a reference so the compiler possibly tries to return x as a reference but you told the compiler to destroy x when …

mrnutty 761 Senior Poster

You should either convert the a into a string or adjust your parameters. For example :

template<typename ReturnType, typename InputType>
ReturnType convertTo(const InputType& input){
 stringstream stream;
 stream << input;
 ReturnType val = ReturnType();
 stream >> val;
 return val;
}
//...your LOGMSG function
int main(){
 int a = 100;
 string msg = "type test!!" + convertTo<string>(a) + " times";
 LOGMSG( msg );
}
mrnutty 761 Senior Poster

You need to also make sure its on fixed format. Here is an example :

void printDollars(const float amount){
 //save old states
 std::ios_base::fmtflags oldFlg = cout.setf(std::ios::fixed, std::ios::floatfield);
 int oldPrecision = cout.precision(2);

 cout << "$ " << amount << endl;

 //reset old states
 cout.setf(oldFlg);
 cout.precision(oldPrecision);

}
mrnutty 761 Senior Poster

Just looking at your main, specifically this part :

mySolver.setMathematicalMethod( pointerToMathematicalMethod );
mySolver.solve();

intuitively, I would expect mySolver.solve() just delegate the job to the mathMaticalMethod. So what I am trying to say is that your computeValue(...) function
in your mySolver doesn't make sense to me. It should be contained in the mathematicalMethod.execute() function. So maybe you can set up some hierarchy like so :

#include <iostream>
#include <cmath>

using namespace std;

//Abstract Interface
struct IMathCommand{
	virtual double operator()(const double& value)const = 0;
	virtual ~IMathCommand(){};
};

class ZeroMathCommand : public IMathCommand{
	double operator()(const double& value)const{ return 0.0; }
};
class SquareMathCommand : public IMathCommand{
	double operator()(const double& value)const{ return value * value; }
};
class SinusMathCommand : public IMathCommand{
	double operator()(const double& value)const{ return std::sin(value); }
};
//Add more MathCommand if needed

class MathSolver{
private:
	IMathCommand *mathFunc_;
public:
	MathSolver() : mathFunc_(0){}
	
	void setMathCommand(IMathCommand* cmd){ 
		mathFunc_ = cmd; 
	}
	const IMathCommand& getMathCommand(){
		return *mathFunc_;
	}
	double execute(const double val = 0.0)const{ 		
		if(!mathFunc_) throw std::exception("Math function not set");
		return (*mathFunc_)(val);
	}	
};


int main(){

	MathSolver solver;

	SquareMathCommand sqrCmd;
	ZeroMathCommand zeroCmd;
	SinusMathCommand sinCmd;
	
	solver.setMathCommand(&sqrCmd);
	cout << solver.execute(10) << endl; //output 100

	solver.setMathCommand(&zeroCmd);
	cout << solver.execute(10) << endl; //ouput 0

	solver.setMathCommand( &sinCmd );
	cout << solver.execute(3.14/2.0) << endl; //output 1

	return 0;
}

It could definitely be better, for example not using raw pointers or it might not fit exactly to your needs, but its a start.

mrnutty 761 Senior Poster

Comments is of type string and std::remove returns a ForwardIterator, so your logic is incorrect. I think you want something like so :

string::iterator newEnd= std::remove(splitComment.at(1).begin(), splitComment.at(1).end(), ' ' );
item->Comments = string(splitComment(1).begin(),newEnd);

I can't be certain without seeing more code.

mrnutty 761 Senior Poster

Try this one:

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

vector<string> split(const string& src, const string& delim){	
	vector<string> result;
	string::size_type startPos = 0, endPos = 0;
	do{
		endPos = src.find_first_of(delim,startPos);
		string::size_type length = endPos - startPos;
		if(length != 0)
			result.push_back( src.substr(startPos,length) );
		startPos = endPos + 1;
	}while(endPos != string::npos);
	return result;
}
template<typename ForwardIterator>
void print(ForwardIterator begin, ForwardIterator end, const std::string& delim = " "){
	while(begin != end) cout << *begin++ << delim;
}
int main(){ 
	string whiteSpaces("\t\n ");
	vector<string> tokens = split("I\tmake no	gaurentess of|what|this,function.does",whiteSpaces + "|,.");
	print(tokens.begin(), tokens.end(),"\n");
}
mrnutty 761 Senior Poster

Here is its documentation.

mrnutty 761 Senior Poster

I think he means to delete tail.
@OP: during a list implementation you will have a lot of transversal and deletion code, for that you might want to make a helper function to make your functions clearer. Also your code doesn't work if there is only 1 element, where the head and the tail point to the same element.

mrnutty 761 Senior Poster

I don't think there is a way around this with C++, in C++0X array initializer comes close. But in C++ you will have to something similar as shown above. You can control the scope of data for example like so :

void initialize(Map& map){
  data1 ...
  data2 ..
}

and so that way you control the memory a little bit more.
Alternatively you can use a file to initialize the map by loading the data into a vector and using the second approach.

mrnutty 761 Senior Poster

Using boost would make it easier for you, for example :

#include <iostream>
#include <string>
#include <map>
#include "boost/shared_array.hpp"
using namespace std;

typedef boost::shared_array<float> Array;
typedef std::pair<string,Array> MapElement;
typedef std::map<string,Array> Map;

MapElement makeElement(const string& str,float* data){
	return MapElement(str, Array(data));
}

int main(){

	Map m = Map();
	float data1[] = {1,2,3,4,5,6,7,8,9,0};
	float data2[] = {65,23,232,545,123,0,-2343};
	m.insert( makeElement("i",data1) );
	m.insert( makeElement("j",data2) );

}

Or you can use just stl's std::vector instead of pointers like so:

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

typedef std::map<string,std::vector<float> > Map;
typedef std::pair<string,std::vector<float> > MapElement;

template<size_t SIZE>
MapElement makeElement(const std::string& str, float (&ptr)[SIZE]){
	return MapElement(str,std::vector<float>(ptr,ptr+SIZE));
}
template<class ForwardIterator>
void print(ForwardIterator& begin, ForwardIterator& end){
	while(begin != end){
		cout << *begin++ << " ";
	}
}
int main(){
	float data1[] = {1,2,3};
	float data2[] = {4,5,6,7,3};
	Map m = Map();
	m.insert( makeElement("i",data1) );
	m.insert( makeElement("j",data2) );
	Map::const_iterator itr = m.begin();
	while(itr != m.end()){
		cout << itr->first << " ";
		print(itr->second.begin(),itr->second.end());
		cout << endl;
		++itr;
	}
}
mrnutty 761 Senior Poster

You need to seed :

#include <iostream>
#include <ctime>

char getRandomLowerCasedLetter(){
 return 'a' + (rand() % ('z'-'a'));
}

int main(){
 //seed the random number generator
 srand( time(0) );
 bool keepPlaying = true;
 char winningLetter= getRandomLowerCasedLetter();
 while(keepPlaying){
     cout << "\nGuess a letter : ";
     char guessLetter = 0;
     cin >> guessLetter;
     if(guessLetter == winningLetter){
        cout << "You Win\n";
        cout << "Play again <'y' = yes, 'n' = no> : ";
        char play;
        cin >> play;
        if(play == 'y') keepPlaying = true;
        else keepPlaying = false;
        winningLetter = getRandomLowerCasedLetter();
     }
 }
}
mrnutty 761 Senior Poster

The best way is to get the original coder to explain it to you. If thats not possible, use the code( if you need to ) for your needs as long as you know what its supposed to do and not necessarily how it does it. If all fails then you just read it step by step. Use the debugger if you need to, start from main and follow its execution( if possible ), and go from there.

mrnutty 761 Senior Poster

>>std::cout << "ans->" << *(iptr + i) << std::endl;
>>std::cout << "ans->" << *(*tptr + i) << std::endl;

Just for clarity, it would be better to use array notation:

std::cout << "ans->" << iptr[i] << std::endl;
std::cout << "ans->" << tptr[0][i] << std::endl;
mrnutty 761 Senior Poster

For the second one. Remember, toipArray can have its own address. What it points to is key.
And in your case it points to an array of ints. If that didn't answer your question, then please re-phrase it. I wasn't able to read it clearly.

mrnutty 761 Senior Poster

Also just to point out again, doing premature optimization is bad. It will make your code non readable and unclear and just plain bad. So start optimization if you need to after your done with the program, and NOT DURING.

mrnutty 761 Senior Poster

Just some tips:

1) Make your program first, make it reasonable and clear and readable
2) Then run it and see if it meets your program requirements
3) If not then profile it with a profiler and fix the hotspots

mrnutty 761 Senior Poster

You want something like this :

int getIntGrade(char letter){
 if(letter == 'A' || letter == 'a') return 95;
 if(letter == 'B' || letter == 'b') return 85;
 //and so on
}

And if you want to go the other way it would look something like this.

char getLetterGrade(int grade){
 if(grade > 90) return 'A';
 else if(grade > 80) return 'B';
 //and so on
}
mrnutty 761 Senior Poster

You should make the whole iterator class templatized.

mrnutty 761 Senior Poster

@OP: maybe you should use a 1D array to implement a 2D array, using the index conversion, ROW_SIZE*row_index + col_index

mrnutty 761 Senior Poster

Just use the C++ random_shuffle, its been tested for its distribution so its most likely good enough.

mrnutty 761 Senior Poster

This is not quite right: You need to restrict the swapping so that the destination position is always >= the source position.

int rowToSwap = a random valid row that is >= row
int colToSwap = rowToSwap == row?
    a random valid row that is >= col :
    a random valid row

To see why, consider what happens if there are only two elements in the array using the original strategy. We look at the first element and swap it with the second with probability 0.5. Then we look at the second and swap it with the first with probability 0.5. The net effect is to keep the original ordering 3/4 of the time. Not a random distribution.

Oh I see. But if the probability of swapping is 0.5 per say, then the probability of swapping 2 times in a row is 0.5*0.5 = 0.25? So isn't the probability of keeping the original order 1/4? But either way its not equal distribution. So I see your point. Is there a induction proof on the equal random distribution on this method? Just curious.

mrnutty 761 Senior Poster

Is there anyway you can change the design of the program so it doesn't rely on compile time ifs? Seems like you want to implement state machine.

mrnutty 761 Senior Poster

Just some skeleton to help you visualize whats been said above :

for row = 0 to ROW_SIZE
    for col = 0 to COL_SIZE
         int rowToSwap  = a random valid row
         int colToSwap    = a random valid col
         swap array[row][col] with array[rowToSwap][colToSwap]
mrnutty 761 Senior Poster

Create another JPanel, and add the toolbar to that JPanel. And think of that new panel as a toolbar.

mrnutty 761 Senior Poster

Ok show us how/where you call the allocation for texture. Presumably, you only need to allocate once for the texture.

mrnutty 761 Senior Poster

Try using this to hash strings:

unsigned long hash(unsigned char *str){
        unsigned long hash = 5381;
        int c;

        while (c = *str++)
            hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

        return hash;
    }

Then you can incorporate this for the person's last and first name. The algorithm above was found in google.

tylerjgarland commented: While I understand his answer, the google sarcasm is not helpful. I understood hashcode, I just needed help fitting it into a closed array. +0
mrnutty 761 Senior Poster

Your definition of bar() is technically correct syntax, but your usage is illegal because you are returning a reference to a local variable

Correction. bar() returns a copy of the text "world".

mrnutty 761 Senior Poster

I did this for my university like 3 years ago. The exact same problem. I still have it, for a price.

jon.kiparsky commented: Funny. +0
mrnutty 761 Senior Poster

There is no need to redefine true/false.

mrnutty 761 Senior Poster

What exactly is the problem?

mrnutty 761 Senior Poster

Discard the char* and use std::string

mrnutty 761 Senior Poster

You cannot as of right now, seperate the template definition from its implementation. They both need to go in the same file.

mrnutty 761 Senior Poster

You cannot do that in C++.

mrnutty 761 Senior Poster

For you exception handling, it would make sense if you propagate the exception to the client instead of throwing it yourself and catching it. If thats the case then you need not to throw any exception, you can simply use a boolean statement. And to further extend your exception handling, create your own exception class call it NegativeDimensionException which extends from the java standard exception. Then you can throw a more meaningful exception which lets the user know what to specifically to expect. Its just an idea.

mrnutty 761 Senior Poster

The only way that loop terminates is if result = true and current.getNext() = null.

What you want is the binary AND logical operation not the binary OR logical operation.
Also there is no need for line 10. result will stay false unless it is true, and if it is true then the target is found and you can break.

The result in the while loop is really not needed, you can simply use a break statement like so :

public boolean contains(Celebrities target){
 LinearNode<T> start = contents;
 boolean isFound = false;
 while(start.getNext() != null){
   if(_equal(target,start)){ 
       isFound = true; break;
    }
  start.moveForward();
 }
 return isFound;
 }
}
mrnutty 761 Senior Poster

As of right now, C++ does not allow you to separate template header and its definition.
You need to put the template definition in the same file as the header.

mrnutty 761 Senior Poster

If you do not go towards the better solution of using the above links, then what you want is to use an array. Work by digit by digit.

mrnutty 761 Senior Poster

umm, haven't done opengl for a while, but I think you are looking for gluPerspective(..). Its areguments are the following

void gluPerspective(	GLdouble  	fovy,
 	GLdouble  	aspect,
 	GLdouble  	zNear,
 	GLdouble  	zFar);

So just specifiz zNear to be some negative number and zFar to be an adequate high number and you should be fine.

mrnutty 761 Senior Poster

There is not point for Initialize class to have the member private. You would be better of making them priviate. Also Initialize is a bad name. Call it something more meaningful and clear.

mrnutty 761 Senior Poster

almost, e = 1/0! + 1/1!...

so you have to add 1/0! = 1 to each output.


taylor series representation of the constant e

mrnutty 761 Senior Poster
George Bush 70 77
Barack Obama 70 75 80
Bill Clinton 68 70

Does the general format goes like so :

FirstName LastName score1 score2 ... scoreN

or are there only score1 and score2 for all names?

Either way you should do something like so :

struct President{
 string firstName;
 string lastName;
 President(string f = "", string l = ""): firstName(f), lastName(l){}
};

struct PresidentScoreKeeper{
 President pres;
 std::vector<int> scores;
 PresidentScoreKeeper(){}
 PresidentScoreKeeper(const President& p, const std::vector<int> s = ""): pres(p), scores(s){}
};
class PresidentScoreList{
private:
 std::vector<PresidentScoreKeeper> presidentList;
public:
 void add(const PresidentScoreKeeper& p){ presidentList.push_back(p);}
 //more functionalities
};

std::istream& operator>>(std::istream& inputStream, PresidentScoreList& president){
 string line;
 getline(inputStream,line);//KEY IDEA
 President currPresident= prasePresidentName(line);
 std::vector<int> currentPresidentScore= prasePresidentScores(line);
 president.add( PresidentScoreKeeper(currPresident,currentPresidentScore) );

 return inputStream;
}

The key thing is to use getline(inputStream,line). That is, you need to read a line by line for each line in the file instead of character by character.

mrnutty 761 Senior Poster

change this calculation function_one(calculation addition) to this calculation function_one(calculation& addition) and realize the difference.

mrnutty 761 Senior Poster

Before resorting to inheritance, can you state your actual problem with some actual context? Maybe you have been going about this problem wrong?

mrnutty 761 Senior Poster

@OP: Forget you ever saw that code. Its useless.This insertion-sort_recur(a, n-1);//how does this line work acts like a for loop. It keeps going until it reaches the second element. Then it returns to the third element. Then to the fourth and so on...

mrnutty 761 Senior Poster

@FBody: I don't think thats the problem, because he uses end just like you did in your for loop, for comparisons. And in the line he was pointing to, it definitely shouldn't have a bad pointer exception, if his code were working.

@OP: Can you show us that HList is? I'm guessing its like a Array<list<int>> or something? But more importantly, do you have elements stored at HList for each i?

mrnutty 761 Senior Poster

We'll the situation really didn't call for generic. And to be quite honest, using generic in this situation isn't a good design nor is it flexible.

mrnutty 761 Senior Poster

Couple of ways, one way is to do the following :

//interface
struct Conditional{
 virtual bool preCondition()const=0;
 virtual bool postCondition()const=0;
};
//adapter for default
struct ConditionalTrueAdapter: Conditional{
 bool preCondition()const{return true;}
 bool postCondition()const{return true;}
};

//interface
struct Command{
 virtual void execute()=0;
};

class PauseGameCommand : public Command{
private:
 Conditional condition;
public:
 PauseGameCommand(const Conditional& c = ConditionalTrueAdapter())
 : condition(c){}

 void execute(){
   assert(p.preCondition());
   /* code to pause game goes here */
   assert(p.postCondition());
 }
};

Use it like so :

if(user.clickedPauseGame()){   
   PauseGameCommand();
}
else if(user.clickedExitGame()){
  Conditional c = GameState.getGameCondition();
  PauseGameCommand(c); // for example, say, preCondition checks if it can be paused, and postCondition checks if everything went well
}
mrnutty 761 Senior Poster

try putting void stringcomp(string str); right before "int main()".
Also I hope you got a "stringrec.h" that has the prototype of the functions defined in "stringrec.cpp"