mrnutty 761 Senior Poster

Just one more things, for question 2, its not a char type, its a array to chars, which is why in the above post, you see an array of chars

mrnutty 761 Senior Poster

Okay, so if I want to switch everything over from my Vec and Mat to valarray, will I lose any functionality?

I use the .push_back() function sometimes, and I resize vectors on occasion.

Secondly, would this be the way to go about it?...

#include <valarray>
using namespace std;

typedef valarray<double> Vec;
typedef valarray<Vec> Mat;

If it is that simple then it seems I wouldn't have to edit my actual code much, except to simplify things of course.

unfortunately, valarray doesn't behave the same as vector or doesn't have the same interface. So maybe your better off using std::transform. Or create a push_back method for the valarray and the resize method as well

mrnutty 761 Senior Poster

But if you don't want to use that, then check out std::tranform

Here is an example of use :

#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>
#include <iterator>
#include <cmath>
using namespace std;


template<typename ITR>
void print( ITR begin, ITR end){
	while(begin != end) cout << *begin++ << " ";
	cout << endl;
}
int main(){
	int data[] = {1,4,9,16,25};
	typedef std::vector<int> Array;
	Array src(data,data + sizeof(data)/sizeof(*data) );
	Array dest;	

	
	cout << "Before: ";
	print(src.begin(),src.end());

	std::transform( src.begin(), src.end(), //our source
					std::back_insert_iterator<Array>(dest), //our destination					
					std::bind2nd(std::multiplies<int>(),2) //multiply by 2 to each number
					);

	cout << "After: ";
	print(dest.begin(),dest.end());
}
mrnutty 761 Senior Poster

Your using the wrong structure, check out std::valarray

mrnutty 761 Senior Poster

>>#define J sqrt(-1.0)

there is no such thing as sqrt(-1.0), the parameter to sqrt shouldn't be negative. Instead just imagine the second paramter of complex type is imaginary.

typedef std::complex<float,float> Complex;
typedef std::vector<float> TimeDomainData;
typedef std::vector<Complex> FrequencyDomainData;
int main(){
 const int SAMPLE_POINTS = 1024;
 const TimeDomainData data = generateTimeDomainData(SAMPLE_POINTS); //or something
 FrequencyDomainData freqData;
 for(int n = 0; n < SAMPLE_POINTS; ++n){
    const float theta = 2 * PI * n/SAMPLE_POINTS ; //straight from definition
    const float realValue = std::cos(theta);
    const float imaginaryValue = std::sin(theta)
    freqData.push_back( Complex(realValue,imaginaryValue) );
 }
}
mrnutty 761 Senior Poster

Blood, sweat and tears is my choice of drink and a true mans choice as well

mrnutty 761 Senior Poster

Hmm, overkill maybe? That whole process can be accomplished with a non-member function, and the approach can be made fully generic (for types that support operator>>) with argument type deduction:

#include <iostream>
#include <istream>
#include <sstream>
#include <string>

template <typename T>
bool get_next(T& value, std::istream& in = std::cin)
{
    std::string line;

    try {
        if (std::getline(in, line)) {
            std::istringstream iss(line);

            if (iss>> value >> std::ws && iss.eof())
                return true;
        }
    } catch (...) {
        // Collect all exceptions into a failure result
    }

    return false;
}

int main()
{
    float num;

    while (!get_next(num))
        std::cerr<<"Invalid input, please try again: ";

    std::cout<<"Your number is "<< num <<'\n';
}

The problem, of course, is your assumption that there's one item of input for each line. You'll find that as you adjust the solution to allow multiple items per line, it begins to look more and more like how the standard library does things. ;)

Yea I know, buts its no fun when the answer is simple :(

mrnutty 761 Senior Poster

OP probably won't understand this completely right now, but just for giggles here is a generic approach-ish.

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


//Used to convert between types
template<typename S,typename T>
struct SStreamConverter{
 S operator()(const T& in)const{ 
    stringstream ss; 
    S ret = S(); 
    if( !( (ss << in) && (ss >> ret) ) ) throw std::exception();
    else return ret;
 }
};

//used to check if a input is a valid type
template<typename T>
struct IsType{
	template<typename InputType>
	bool operator()(const InputType& s)const{
		std::istringstream stream(s);
		T instance;
		return ((stream >> instance) && (stream >> std::ws) && stream.eof());
	}
};

//An exception representing invalid input error
struct InvalidInputException : std::exception{
	InvalidInputException(): std::exception("Error: Invalid input detected")  {}
	InvalidInputException(const std::string& errorMsg): std::exception(errorMsg.c_str()){}
};

//An Input Grabber from the stream
template<typename T,typename Validator = IsType<T>, typename Converter = SStreamConverter<T,std::string> >
class Streamer{
private:
	Validator isValid;
	Converter convertTo;
public:
	//tries to get the input once	
	T get(istream& stream = cin)const{
		std::string input;
		T result = T();
		getline(stream, input );
		//check for valid input
		if(!(isValid(input)) ) throw InvalidInputException();
		try{ result = convertTo(input); }
		catch(std::exception&){ throw InvalidInputException(); }
		return result; //return if everyting if good
	}
	//tries to get the input until a valid once is detected
	T getUntil(const std::string& errorMsg = "Invalid Input detected, try again\n",istream& stream = cin)const{
		T result = T();
		bool validResult = true;
		do{
			try{
				result = get(stream);
				validResult = true;
			}catch(std::exception&){ 
				validResult = false; 
				cout << errorMsg;
			}
		}while(!validResult);
		return result;
	}
};

int main(){
 Streamer<float> streamer; 
 try{
	 float …
mrnutty 761 Senior Poster

You can't compare character arrays like that. Your best bet is to create a function that will do a loop check of each element in the two arrays. And have it return a boolean.

aka

bool isEqual(char onFile[], char checking[])
{
	for(int i = 0; i < (sizeof(onFile) / sizeof(char)); i++)
	{
		if(onFile[i] != checking[i])
			return false;
	}

	return true;
}

That wont always work like you think it does, specifically, the onFile[] and checking[] gets degraded to a pointer, thus the size information is lost, so you can't use sizeof operator. You should either have a size parameter, or recalculate its size again.

mrnutty 761 Senior Poster

@firstperson

How am I creating my project? I am sorry but what's that question supposed to mean?

You possibly might have created a project with wrong dependencies. When I say create a project, I mean with code blocks. Maybe you have created the wrong type of project. Else you need to manually link the needed headers.

mrnutty 761 Senior Poster

To see if a number is even you can just check the remainder when divided by 2 or check the last bit. For floating number, you can just check the integer part, so there is no need to use fmod since comparing it to 0.0 might not do what you expect everytime.

float f1 = 123.3243f;
cout << (int(f1) % 2 == 0 ? "even" : "odd" ) << endl;
mrnutty 761 Senior Poster

How are you creating your project?

mrnutty 761 Senior Poster

I don't get you problem, this is what I get for input of 3000.

pppppp   oooooo  w   w   w eeeeeeee rrrrrrr      cccccc   oooooo
p     p o      o w   w   w e        r      r    c      c o      o
p     p o      o w   w   w e        r      r    c        o      o
pppppp  o      o w   w   w eeeeee   rrrrrrr     c        o      o
p       o      o w   w   w e        r      r    c        o      o
p       o      o w   w   w e        r      r    c        o      o...
p       o      o  w w w w  e        r      r    c      c o      o...
p        oooooo    w   w   eeeeeeee r      r     cccccc   oooooo ...

 KW/H Used      Rate    Charge       Tax     Total
      3000     0.001         3      0.15      3.15

all I did was add a cout << endl; in line 23. Isn't that what you expected?

mrnutty 761 Senior Poster

Thanks, that sure helped me. The code is here for anyone that might want to take a look at it:

int n;
	double sum = 0;
	//promt user to enter the number.
	cin>>n;
    for (int i = 0; i<=n; i++)
    {
    sum+=i;
    }
	cout<<sum <<endl; //demonstrating the result

This gives you the sum of 0 + 1 + 2 + ... + n

You want the sum of 1/1 + 1/2 + 1/3 + ... + 1/n

So instead of each term being i, you need it to be its inverse.

mrnutty 761 Senior Poster

You want ifstream in(foom.c_str());

mrnutty 761 Senior Poster

Wow are we really having a 4 page long thread about this. I don't get whats the problem. You guys/girls/its needs to get some fresh air and forget this thread ever happened

WaltP commented: Especially since the OP has made 1 single post. +16
mrnutty 761 Senior Poster

If your ultimately wanting to play sound then I would suggest using a library that handles reading and playing sounds for you already. A suggestion would be to use FMOD. Or if you just want to develop on windows then you can use the PlaySound function

mrnutty 761 Senior Poster

I don't see anywhere stated that int main(int argc, char* argv[]) is better than int main() .

I wonder whether char main() is acceptable?

Quoted from wiki-god


C and C++
In C and C++, the function prototype of the main function looks like one of the following:
int main(void)
int main(int argc, char *argv[])

The parameters argc, argument count, and argv, argument vector,[1] respectively give the number and value of the program's command-line arguments. The names of argc and argv may be any valid identifier in C, but it is common convention to use these names. In C++, the names are to be taken literally, and the "void" in the parameter list is to be omitted, if strict conformance is desired.[2] Other platform-dependent formats are also allowed by the C and C++ standards, except that in C++ the return type must stay int; for example, Unix (though not POSIX.1) and Microsoft Windows have a third argument giving the program's environment, otherwise accessible through getenv in stdlib.h:

There was no extra emphasis in the original statement, I just put emphasis on the important statement pertaining to your question.

So both version are valid, neither one is better than the other. Use int main() if you don't need the command line arguments,
or use int main(int argc, char *argv[]) if you do need the command line argument. In C++, if you do need the command line argument, then to conform to standards, you need …

mrnutty 761 Senior Poster

Check if your compiler supports export keyword, although note that its being removed from the standard.

mrnutty 761 Senior Poster
if (currentDay = 0)

you want to compare not assign, in another words

if (currentDay == 0)

do that for all of your similar if statements

mrnutty 761 Senior Poster

Forgot to mention you need to use fixed format:

double d = 5.0;
cout << fixed << setprecision(1) << d << endl;
mrnutty 761 Senior Poster

You can simply append 0 since it does nothing:

string toString(const double d, int nZero = 0){
 stringstream stream;
 stream << d;
 return stream.str() + string(nZero,'0');
}

If you use the double value to print out the value then you can set its precision like so :

double d = 5.0;
cout.precision(4);
cout << d << endl;

or using <iomanip>

double d = 5.0;
cout << setprecision(4) << d << endl;
mrnutty 761 Senior Poster

just look at what it gets and you'll see:

int x = 0;
while(cin >> x) { continue;}
cin.clear();
//discard junk and print out whats being discarded:
char ch = 0;
while(cin.get(ch) && ch != '\n') cout << "Discarding'" << ch << "'" << endl;
mrnutty 761 Senior Poster

A hint, read the definition of a binary tree, then see how it applies to the trees's children.

mrnutty 761 Senior Poster

whats this supposed to do:

while( cin.get() != '\n' );

there isn't a body for the while loop.

it reads the stream character by character but doesn't save the read character, it just does nothing with the read character, if we wanted to save the character, we could have done this :

char ch = 0;
while( cin.get(ch) && ch != '\n') { 
 //do something with ch variable, which contains the read junk character
}
mrnutty 761 Senior Poster

It first reads 2, and stores it in x. It then reads 4 and stores it in x. Reading is done so now it executes the body. The 6 you entered also, does not get read into x or y just yet, because the stream already read 2 and 4, so the 6 stays in the stream for later, so when you entered 8, in the stream there will be 6 and 8 now, 6 gets read into x and 8 gets read into y, and the body executes.

mrnutty 761 Senior Poster

In the first while loop your exit condition is when cin fails. It will fail when it reads in something that its no supposed to. Its expecting a integer( a number ), and if you pass it a character, then cin fails and it sets the failure bits accordingly.

Now in your second loop, cin is still in a fail state because you haven't reset the cin stream, thus the failure bits are still set and thats why it doesn't execute. To solve your problem, you need to reset the input stream.

int x = 0 ;
while( cin >> x) { cout << "read : " << x << endl; }
//if we are here, then cin failed so we need to reset the stream
cin.clear(); //clear or reset the failure bits
while( cin.get() != '\n' ); // throw away any junk that is in the stream after failure
int y = 0;
//now cin is reseted so use it normally
while( cin >> y ){ cout << "read : " << y << endl; }
mrnutty 761 Senior Poster

I don't see anything wrong. I would suggest for good practice also setting your pointers to null when you deallocate them. I sometimes like to define delarr in a preprocessor macro:

#define delarr(X) (delete[](X));((X)=0)

Hope this helps. (Also I may be wrong so more people should check as well)

If good practice is what your after, then it would be a good practice to use standard containers.

mrnutty 761 Senior Poster

idk too much about jQuery but it seems you can abstract:

<script>
function foo(name,id)
{
       var $j = jQuery.noConflict();
	$j(function() {
	    $j(name).click(function(evt) {
		$j(id).load("content.php?order=most&f=recent")
		evt.preventDefault();
	    })
	})

}

 foo("mostrec","#1");
 foo(".leastrec","#1");
 //...so on
</script>
Pinchanzee commented: Simple + effective +2
mrnutty 761 Senior Poster
mrnutty 761 Senior Poster

Sucks at it happens. Thats why once a while you should hit cntrl-s( save shortcut ). This happened to me many times, and I learnt my lesson.

mrnutty 761 Senior Poster

>>@firstPerson: >> because reference needs to be pointing to a valid object
That is not strictly true. References can point to invalid objects (or deleted objects). But it is true that it is much harder to make that bug happen with references, while it is a lot easier to make that error with a pointer.

Yea yea yea, I glanced over that topic in my head but didn't write it down because I didn't think it was noteworthy for this thread, but thanks for mentioning it.

mrnutty 761 Senior Poster

Thank you for your reply..that's what i thought from the beginning, that i would definitely have a memory leakage..But my example works perfectly when i try to use my table's data, even if i didn't deallocate it correctly..Why is this happening?

Just because you have a memory leak doesn't mean your program will not work,it just mean that you are leaking memory.

mrnutty 761 Senior Poster

>>So I found that there was a difference between passing by pointer and by reference with by reference being safer. I'd like to understand why so that I can learn what is best to use when

Yes reference can be safer and most likely will be, simply because reference needs to be pointing to a valid object, where a pointer can point to an invalid object( i.e null object type )

mrnutty 761 Senior Poster

Yes in that for-loop example there would be a memory leakage if you don't deallocate the tab before reallocating memory for it again.

&tab means take the address of tab, in which if tab is an array, then when you pass it into a function, it decays into a pointer, so you will effectively be taking an address to a pointer, in which the pointer points to an array of elements.

mrnutty 761 Senior Poster

Both example are similar, no you do not have a memory leak although there might be subtle problems with your first example. In general, use reference when possible instead of pointers. I'm sure mike below me will give you a more elaborate answer soon.

mrnutty 761 Senior Poster

Should u not decrement objectCount in Destroy function?

mrnutty 761 Senior Poster

Can this not be done without a constructor?
Because we haven't learnt that yet... it's our next chapter, though.

Yes, it can. A viable solution to this problem is to create a base counter class that is templatized. But I assume you haven't learn that before. So for now you can just create a counter variable and increment it in the proper place and decrement it in proper place. As suggested, use a static count variable, ex.

class People{
private:
 static unsigned PEOPLE_COUNT; //this creates one people_count variable for all class People class object
public:
 People(); //increment it here
 ~People(); //decrement here
 People(const People& p); //what is this, what should u do here?
 People& operator=(const People& p) ; //what should u do here?
 //...are there any other place you should worry about?
};
mrnutty 761 Senior Poster

Your question is kind of vague, but possible any one of these :

string->size(); //if you are using std::string *
strlen(string); //if you are using c-style string
mrnutty 761 Senior Poster

As suggested the easiest way to achieve it is using std::string as follows:

std::string getClampedInput(const int maxSize){
 string str;
 getline(cin,str);
 int clampedSize = maxSize > str.size() ? str.size() : maxSize; //make sure maxSize is not greater than input size
 return str.substr(0,maxSize);
}

another way is to do it is using cin.get, but the above method is the easiest.

mrnutty 761 Senior Poster

you can use std::sort. Here is an example :

struct DaniwebMember{
  int ranking;
  int age;
  DaniwebMember() : ranking() , age() {}
  DaniwebMember( int r , int a ) : ranking(r) , age(a){}
};
bool compareByRanking(const DaniwebMember& m1, const DaniwebMember& m2){ return m1.ranking < m2.ranking; }
bool compareByAge(const DaniwebMember& m1, const DaniwebMember& m2){ return m1.age < m2.age; }

int main(){
 DaniwebMember members[100]; 
 //populate members ...
 std::sort( members , members + 100 , compareByAge ) ;//sort by age
 std::sort( members, members + 100, compareByRanking ); //sort by ranking
}

so you see, all you have to do is create a compare function and pass it onto std::sort

mrnutty 761 Senior Poster

I think the simple approach would produce good results, that is defining some DistanceSplit value. For example, consider the data below.

[ 4 12 13 21 30 38 39 45 60 84 90 91 95 96 97 109 113 114 128 148 149 163 175 180 182 184 192 ]

say the distance split is 10, then we would have the following subset
[ [4,12,13,21,30,38,39,45] , [60] , [84,90,91,95,96,97] , [109,113,114] , [128,148,149,163] [175,180,182,184,192] ]

Obviously the lower the distanceToSplit value the more subsets you will have. You can calculate the distanceToSplit by using factors such as the mean,variance and standard deviation.

Does the given data follow some type of patterns?
What does the data represent?
Given the above sample data, what would be the 'correct' subset to you? Can you give us more information on the problem this is going to solve?

mrnutty 761 Senior Poster

Your terms are way to vague. Judging from your example, you can do something like this :

1) Sort the set
2) Define a MIN_DISTANCE_TO_SPLIT
3) Keep a beging / end pointer, both pointing to the start of the sorted list
4) Move the end pointer until a difference of MIN_DISTANCE_TO_SPLIT is observed from element i to i+1 or until you get to the end of the list
5) Now create a subset from [beginPointer,EndPointer]
6) Set begin pointer to endPointer + 1
7) Increment endPointer
8) Repeat from step 4, until an invalid endPointer


What are you trying to solve with this anyways?

mrnutty 761 Senior Poster

1) Replace all instance of 'char' with std::string in your program
2) Don't use 'goto', use conditional loops instead. Imagine there were no 'goto' command, how would you restructure your program accordingly?

mrnutty 761 Senior Poster

Casting in that example if fine. But looking at your code, you are probably going to want to encapsulate the member variables, that way operator< does not have to be a friend function.

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

class StrategyKey
{
public:
	StrategyKey(){}
	~StrategyKey(){}

	StrategyKey(const char* strA):
		str_strategy(strA)
	{}
       virtual const std::string& getStrategyValue()const{ return str_strategy; }
private:	
	std::string str_strategy;
};

class TechniqueKey : public StrategyKey
{
public:
	TechniqueKey(){}
	~TechniqueKey(){}

	TechniqueKey(const char* strA, const char* strB): StrategyKey(strB),
		str_technique(strA)
	{}
        const std::string& getStrategyValue()const{ return str_strategy; }
private:
	string str_technique;
};

bool operator< (const StrategyKey& stratKeyA, const StrategyKey& stratKeyB){
 return stratKeyA.getStrategyValue() < stratKeyB.getStrategyValue();
}

bool operator< (const TechniqueKey& stratKeyA, const TechniqueKey& stratKeyB){
 const int cmp = stratKeyA.getStrategyValue().compare( stratKeyB.getStrategyValue() );
 if( cmp != 0 ) return cmp < 0;
 else{ //same so compare base values
   return dynamic_cast<const StrategyKey&>(stratKeyA) < stratKeyB; 
 }
}
Jsplinter commented: Thanks! I need to read up on friend functions. +2
mrnutty 761 Senior Poster

>> while((e!=0) || (i<5));

I think you want to change that to while((e!=0) && (i<5)); I would suggest restructuring your program using functions and std::vector

mrnutty 761 Senior Poster

Look into opengl

mrnutty 761 Senior Poster

You should be using std::vector and std::string. Thus assuming that, you can do the following :

bool found = std::find( vectorOfStrings.begin(),vectorOfString.end(),stringToFind) != vectorOfString.end();
mrnutty 761 Senior Poster

saw that Narue posted first but it still adds a bit more info

no. srand sets the seed, it doesnt generate random numbers. the seed is a number that rand uses to generate random numbers.

rand potentially generates large numbers but some maths is all you need to put some boundaries on it:

x = rand() % 10;

the % sign is modulus, it calculates the remainder from the division (divide by 10 in this case). so thinking about it, this means that x could only equal a number from 0 - 9.

about time(0), http://cplusplus.com/reference/clibrary/ctime/time/
time takes an argument which tells it where to store the time, if it is 0, then it returns it.

Just note that using the modulus operator works on the low order bits, although in some implementation
they are just as random as the high order ones, but for consistency one should use the high order bits. For example one could
generate a random number from 1-10 as follows.

int lowOrderRand = rand() % 10 + 1 ; // "random" number from 1 - 10 , uses low order bits
int highOrderRand = 1 + int( 10.0 * (rand()/(RAND_MAX+1)) ); // "random" number from 1 - 10, users high order bits
mrnutty 761 Senior Poster

Sorry, I miswrote it then. I was suggesting what Kanosia said -- "change animation a in a stepwise manner each update call". Didn't mean to make it look like the way it did.