mrnutty 761 Senior Poster

You can use cin.get() to read each individual characters from the stream.

mrnutty 761 Senior Poster

Your almost there. All you have to do is set the parameter to the function, for example you can do this :

void sort_sale(double sale[], int n);
int main(){
 const int n = 7;
 //...
 double sale [ n ] = {0, 0, 0, 0, 0, 0, 0};
 sort_sale(sale,n);
 
}

You don't have to change much, just add the correct parameter to each function.

mrnutty 761 Senior Poster

Your almost there. All you have to do is set the parameter to the function, for example you can do this :

void sort_sale(double sale[], int n);
int main(){
 const int n = 7;
 //...
 double sale [ n ] = {0, 0, 0, 0, 0, 0, 0};
 sort_sale(sale,n);
 
}

You don't have to change much, just add the correct parameter to each function.

mrnutty 761 Senior Poster

Are you interested in the physics or its visual appreance? For the physics part, you can simply model the bulets by a vector that travels straight in its direction. But i'm not completely sure what exactly you need.

mrnutty 761 Senior Poster

Well what do you intend to use the heightmap for? One use for them is to create a terrain based on the heightmap. For example, you would use the heightmap values to map the height of the plane at a given point.

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

How is the char being initialized?

mrnutty 761 Senior Poster

I'm still not exactly sure what you are trying to do. Can you give me a full example and then we can possible show you a non temporary solution.

mrnutty 761 Senior Poster

Try something like this.

string praseLine(const std::string& line){
 /* prase the line and return the prased line */
}
int main(){
 string prasedContent;
 string fileName("test.txt");
 ifstream fileIn(fileName.c_str());
 string line;
 while( getline(fileIn,line) ){
  string prasedLine =  praseLine(line);
  prasedContent += prasedLine;
 }
 doStuff(prasedContent);
}
mrnutty 761 Senior Poster

>>Can someone explain to me what I am doing wrong
EVERYTHING

This is what you want :

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

int main(){
 string line;
 getline(cin,line); //read a line
 /* do stuff with the line */
}
WaltP commented: OP asked for what he's doing wrong, not just code that fixes the problem. -3
mrnutty 761 Senior Poster

Can you settle for something like this :

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

template<typename T>
class Table{
private:
	class TWrapper{
	 private:
		T value_;
		bool isNull_;
	public:
		TWrapper(const T& val = T(), bool isnull = true) : value_(val), isNull_(isnull){}
		bool isNull(){ return isNull_;}
		void isNull(bool b){ isNull_ = b; }
		T& get(){ return value_;}
	};
private:
	typedef TWrapper Element;
	typedef std::vector<Element> TableType;
	TableType table;
public:
	Table(){};
	Table(int size){ _init(size);}
	void setAt(int index, const T& value){
		table[index] = Element(value,false);
	}
	T& getAt(int index){ return table[index].get(); }
	bool hasElementAt(int index){
		return _isValidIndex(index) && !table[index].isNull();
	}
	int size(){
		return table.size();
	}
private:
	bool _isValidIndex(int i){ 
		return (i >= 0 && i < (int)table.size() ); 
	}
	void _init(int size){
		table = TableType(size,Element()); //{null....null}
	}
};
int main(){	 
	Table<int> table = Table<int>(3);  //can assume table contains {null null null}
	cout << boolalpha;
	for(int i = 0; i < table.size(); ++i){
		if(table.hasElementAt(i)) cout << table.getAt(i) << endl;
		else cout << "No element at index : " << i << endl;
	}

	table.setAt(0,150);
	table.setAt(2,100);
	
	for(int i = 0; i < table.size(); ++i){
		if(table.hasElementAt(i)) cout << "\nAt index " << i << " = " << table.getAt(i);
		else cout << "\nNo element at index : " << i;
	}
	cout << endl;
}

basic idea is to wrap the type T. Its less efficient, but possible does what you want.

mrnutty 761 Senior Poster

@OP: Trust me on this. Using singleton is rarely justified, I mean rarely. Just create only create a single object from the class. For your example, see the previous post using static variables, and such.

mrnutty 761 Senior Poster

You only need to seed it once. So at the beginning of main, put the srand stuff. and take that out of your random function.

mrnutty 761 Senior Poster

Forget about Singleton, its an antipattern. For you case, go with a more object oriented approach and define the variables in a class or namespace with appropriate context. For example :

class Window{
public:
 static const int SCREEN_WIDTH = 100;
  //...
};

or maybe :

namespace Environment{
  namespace PhysicsConstants{
      const float PI = 3.14f;
      const float GRAVITY = 9.18;
      ///...
  }
};

and as suggested, you can also just pass around the variable when needed via appropriate parameter list.

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

First you need to play music, check this out. Google and see what you get.

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

You need to wrap line 16 to line 28 with a loop like so :

int Input, FirstInterval = 0, ...
int MAX_INPUT = 10;
for(int i = 0; i < MAX_INPUT; ++i){
   int input = ask("How many marks did the student recieve");
   if(input < 29){ ... }
   else if(input < 39) { ... }
   else if(input < 69) { ... }
}
 /* printGraph(...);
mrnutty 761 Senior Poster

This is what you want to do :

#include <iostream>

using namespace std;

void printGraph(const int max){
 for(int i = 0; i < max; ++i){
   cout <<"*";
  }
 cout << endl;
}
int main()
{
   int i, j;
   int count;
   int Input, FirstInterval = 0, SecondInterval = 0, ThirdInterval = 0;

   cout << "How many marks did the student recieve?" <<endl;
   cin >> Input;
   
   if ( Input < 29 ){
     FirstInterval++;
   }
   else if ( Input < 39 ){
     SecondInterval++;
   }
   else if ( Input < 69 ){
     ThirdInterval++;
   }
   cout << "First interval : ";
   printGraph(FirstInterval);
   cout << "Second interval : ";
   printGraph(SecondInterval);
   cout << "Thrid interval : ";
   printGraph(ThirdInterval);

   return 0;
}
mrnutty 761 Senior Poster

append an else before the second and third ifs.

mrnutty 761 Senior Poster

I'm not sure what exactly you are trying to do. Are you trying to find the max numbers from say {5,6,...17} ? Can you explain your problem a little better.

mrnutty 761 Senior Poster

Make a chart of equation describing each statement

mrnutty 761 Senior Poster

Here is its documentation.

mrnutty 761 Senior Poster

Your getting 64 because thats the size, you have a couple of options :
1) Use string
2) Use std::vector<char>
3) Append a null character at the end
4) Create a length variable to keep tract

for example :

char msg = "12345"; //null character appended automatically
int length = strlen(msg);
char msg2 = {1,2,3,4,5,'\0'}; //append null character automatically 
int length2 = strlen(msg2);

But to make your like easier, if you can, just use std::string.

mrnutty 761 Senior Poster

A guess at what you want :

int n1 = 10;
int n2 = 5;
int n3 = 12;

int min1 = std::min(n1,n2);
int max1 = std::max(n1,n2);
for(int i = min1; i < max1; ++i) cout << i << " ";

int max2 = std::max(n2,n3);
int min2 = std::min(n2,n3);

cout << endl;

for(int j = max2; j >= min2; --j) cout << j << " ";
mrnutty 761 Senior Poster

For the first one, here are some hints :

1) Compute the distance from the first square(north-west) to the last square (south-east) and note that for each square there are upto 8 position on can move.

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

Check this site out. It shows you many bit hacking solutions. If you program in a closed, restricted and limited programming hardware, they come to use.

anishakaul commented: Very helpful link. +2
Onlineshade commented: Good post. +0
mrnutty 761 Senior Poster

Your not going to be able to do this precisely with C++. You need to use graphics API like openGL. But here is some psuedo-code:

void showCoordinate(int x, int y){
 string coord = "(" + toString(x) + "," + toString(y) + ")";
 printOnScreen(coord);
}
template<typename T>
string toString(const T& src){
 stringstream ss;
 ss << src;
 return ss.str();
}
mrnutty 761 Senior Poster

Maybe some psuedo-code will start you up :

//assuming array column size is 3
function mySwap(Array2D array){
 for row := 0 to array.length DO
     swap(array[0],array[2])
}

And if you want it more general then you can do something like so :

function mySwap(Array2D array){
 for row := 0 to array.length DO
    for colStart := 0, colEnd = array[row].length-1 until colStart < colEnd
      swap(array[colStart],array[colEnd])
      increase colStart and decrease colEnd
}
mrnutty 761 Senior Poster

Can you have void doSomething(BaseClass& b){...} in your toplayer?
Maybe you should show some code of exactly what you are trying to do.

mrnutty 761 Senior Poster

I guess you can try the standard functions like sin or cos or tan or sqrt and so on.
If you looking to win the fair/project then you might want to think of something else because comparing operations aren't so valuable or useful.

mrnutty 761 Senior Poster

I will tell you int's will be faster than floats/doubles. And doubles will be faster than floats. But to answer your question yes, you can use ctime header. Here is an example:

#include <iostream>
#include <ctime>

int main(){
  time_t startTime = clock();
   /* code to test goes here */
  time_t endTime = clock();

  cout << "Difference in time(milliseconds) : " << endTime - startTime << endl;
}
matthewkeating commented: Thank you! Awesome answer. +1
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

Make sure your 1st derived print is virtual, if your second derived is derived from your first derived.

mrnutty 761 Senior Poster

The 2D array does not really need a null character. Its the information contained inside that might need it.

mrnutty 761 Senior Poster

check out fmod

mrnutty 761 Senior Poster

Maybe this will help.

#include <iostream>
using namespace std;

int main(){
 char sample[] = "3E";
 int result[1] = {};

 cout << "Encoding : " << sample << endl;

 result[0] = (sample[0] << 8) | (sample[1]) ; //encode

 cout << "Encoded value : " << hex << result[0] << endl;
 cout << char( (result[0] & 0xff00) >> 8) << endl; //decode top 8 bits
 cout << char(result[0] & 0x00ff) << endl; //decode bottom 8 bits
 return 0;
}
mrnutty 761 Senior Poster

sure buts that'll take some code. You should start out first and then add more features after you have the core functionalities working.

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

What you need is General Path to plot.

mrnutty 761 Senior Poster

Depends on what you know. But how about some simulation on pathfinding?

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

Trick question, because at the end they are all the same!

mrnutty 761 Senior Poster

No the point is to work with each digit in the string, not convert the string into a double..