mrnutty 761 Senior Poster

In WinAPI almost all structures and classes are in all caps so that might just be a convention you follow.

True in a sense that it could be a convention one can follow, but it doesn't mean its a good convention. But you have to understand that the windows API is really old. Even the windows API uses all caps for constant data types, but they also use all caps for certain structures. And they also mix up the two, that is use all caps for constant structure. If you were developing the windows api library, then you should follow their convention, but since this is C++, you should follow C++ convention. And although there aren't a standard convention, there are some widely used convention and its best not only for the creator but also for future maintainer to use convention that they will naturally understand.

mrnutty 761 Senior Poster

In C++ I'd use classes and their operators to add the fractions together.

You can play around with overloading the >> and << operators to make calling input/output neater.

#include <iostream>
#include <conio.h>
using namespace std;

class FRACTION
{
	int numerator;
	int denominator;

	public:

	FRACTION()
	{
		cin >> numerator >> denominator;
	}
	FRACTION(int num, int denom)
	{
		numerator = num;
		denominator = denom;
	}

	int GetNumerator()
	{
		return numerator;
	}

	int GetDenominator()
	{
		return denominator;
	}

	friend void operator+=(FRACTION &lhs, FRACTION rhs)
	{
		lhs.numerator = lhs.numerator*rhs.denominator + rhs.numerator*lhs.denominator;
		lhs.denominator *= rhs.denominator;
	}

	friend FRACTION operator+(FRACTION lhs, FRACTION rhs)
	{
		return FRACTION(lhs.numerator*rhs.denominator + rhs.numerator*lhs.denominator, rhs.denominator*lhs.denominator);
	}

};

int main()
{

	cout << "Enter fraction numbers ";
	//using += operator
	FRACTION first, second;
	first += second;

	cout << first.GetNumerator() << "/" <<  first.GetDenominator() << endl;

	cout << "Enter fraction numbers ";
	//using + operator
	FRACTION third, fourth, result(0,0);
	result = third + fourth;

	cout << result.GetNumerator() << "/" <<  result.GetDenominator() << endl;

	getch();
	return 0;
}

Usually ALL_CAPS word are used for constants. So not to confuse future programmers and to promote following convention, please stop promoting this. And also there is no need for getch(), a good IDE will pause your console before exiting, or use cin.

@OP: I'm assuming you don't know about classes and structs yet, so in that case you can pass parameters by reference like so.

#include<cstdio>
#include<iostream>

void addFraction(int n1, int d1, int n2, int d2, int& numerator, int& denominator){
  numerator = n1 * …
mrnutty 761 Senior Poster

>>for(int i = 0; i < (sizeof(animations) / sizeof(Animation)); i++)

I hope you know that, thats only going to run once. And for your error, are you sure its in that line? If what you say is true then it should compile.

Lets see the definition of condition and AnimationCondition.

mrnutty 761 Senior Poster

What firstPerson did was to change 2 to 2.0f which ias a floating point number. This is important because there is no pow(int, int) defined in the math library. For a list of the ways you can use pow() check this out.

Not only that, but he had this inside main

float DistanceofTwoCars(float *car1, float *car2);
	{
		cout << "The Distance between Car 1 and Car 2 is... " << endl;
		cout << endl;
		cout << "D = " << (float)sqrt(pow(car2[0] - car1[0], 2) + pow(car2[1] - car1[1], 2) + pow(car2[2] - car1[2], 2)) << endl;
	};
mrnutty 761 Senior Poster

Can you use std::string?

If not you can do something like this:

void substituteRule(const char *expr, const char *rule, char *result){
   if(!expr) return; 
   else if(expr[0] == 'F') _expand(result,rule); // rule = rule + result; Substitute rule
   else _expand(rule,expr[0]); //else no substitute just add
   substituteRule(expr + 1, rule, result); //else move to next character
}
mrnutty 761 Senior Poster

There are some serious problems with your code. Here is a fix. I'll let someone explain it, because I don't have enough patience right now.

#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>

using namespace std;

void DistanceofTwoCars(float *car1, float *car2){
	cout << "The Distance between Car 1 and Car 2 is... " << endl;
	cout << endl;
	cout << "D = " << (float)sqrt(pow(car2[0] - car1[0], 2.0f) + pow(car2[1] - car1[1], 2.0f) + pow(car2[2] - car1[2], 2.0f)) << endl;
}

int main()
{
	float car1[3]; //Car 1 has 3 coordinates
	float car2[3]; //Car 2 has 3 coordinates

	// Car 1's ( X, Y, Z ) Coordinates
	cout << "What is the X Coordinate of Car 1? ";
	cin >> car1[0];
	cout << endl;
	cout << "What is the Y Coordinate of Car 1? ";
	cin >> car1[1];
	cout << endl;
	cout << "What is the Z Coordinate of Car 1? ";
	cin >> car1[2];
	cout << endl;
	cout << "The coordinates of Car 1 are..." << " ( " << car1[0] << "," << car1[1] << "," << car1[2] << " )" << endl;
	cout << endl;

	// Car 2's ( X, Y, Z ) Coordinates 
	cout << "What is the X Coordinate of Car 2? ";
	cin >> car2[0];
	cout << endl;
	cout << "What is the Y Coordinate of Car 2? ";
	cin >> car2[1];
	cout << endl;
	cout << "What is the Z Coordinate of Car 2? ";
	cin >> car2[2];
	cout << endl;
	cout …
Zvjezdan23 commented: Thank you so much for your help. I really appreciate you helping me out. +0
mrnutty 761 Senior Poster

No pick a better language. Javascript would be a good choice.

mrnutty 761 Senior Poster

I'm not sure where this post fits, but after staggering here and there I Thought I would throw it here!
I find difficult to make coordinates by hand (Not very good at x-y-z though I know the XY coordinate). Is there a tool that will allow you to draw let say a cube and it will give the coordinates for you? I use Ubuntu, but I will not mind if there is windows version!
Thanks

What are you using in conjunction with opengl? Maybe it already has what you are looking for. For example, glut has glutSolidCube(length), where is places the solidCube in the origin. But if not then you could just make a simple function that draw what you want in the origin then transform it from there.

mrnutty 761 Senior Poster

I though it was obvious that Obama was going to get reelected? The main reason being, that during his presidency, Osama was killed.

mrnutty 761 Senior Poster

Any reason you can't use standard facilities?
For example:

#include <iostream>
#include <vector>
#include <algorithm>

struct Equals {
    Equals(int x) : v_(x) {}
    bool operator() (int x) { return v_ == x; }
    int v_;
};

int main () {
    std::vector< int > items;
    for (int i = 0; i < 25; ++i) items.push_back (i % 3);
    int count = std::count_if (items.begin(), items.end(), Equals(2));
    std::cout << "Total number of 2's: " << count << std::endl;
    return 0;
}

to use even more stl,

#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
int main () {
   using namespace std;
    std::vector< int > items;
    for (int i = 0; i < 25; ++i) items.push_back (i % 3);
    int count = std::count_if (items.begin(), items.end(), std::bind2nd(std::equal_to<int>(),2) );
    std::cout << "Total number of 2's: " << count << std::endl;
    return 0;
}
mrnutty 761 Senior Poster

Make your class as such:

class dm_energy_vec
{
public:
        dm_energy_vec(){}
        dm_energy_vec(const vector<float>& vec): m_energy_dep(vec){}
	vector<float> m_energy_dep;
};

and in line 40, change to:

energy_dep_sum.push_back( dm_energy_vec(energy_dep));

but honestly see no point for that class.

mrnutty 761 Senior Poster

You do not want remove, but list::erase. Here is your code with tags and a little more cleaned up:

cout << "Contents: ";
list<FileInfo*>::iterator p = futurelist.begin();
while(p != futurelist.end()) {
  cout << (*p)->submissiontime << " ";
  cout << (*p)->length << " ";
  cout << (*p)->finishtime << " ";
  const int length = (*p)->length;
  if(length < averageBW){
   ++Noactive;
  }else{
   ++Nodelayed;
  }
   p = future.erase(p) //no need to increment p, since .erase returns the next element
}
cout << "\n\n";

But if that doesn't solve your problem, please be more specific.

EDIT: the reason why it james is because after you call .remove(*p), the iterator *p is invalid.

mrnutty 761 Senior Poster

Easy enough, assuming some things.

int maxVal  = INT_MIN;
int minVal = INT_MAX;
int input = -1;
const int END  = -1;
while( cin >> input ){
  if( input == END) break;
  else{
    minVal = std::min(minVal,input);
    maxVal = std::max(maxVal,input);
  }
}
mrnutty 761 Senior Poster
while(begin != end )  
    words[*begin++]++;

is the same as:

while(begin != end )    //<-- I believe the stream iterator is getting input here
 {    
    int count = words[*begin]; //get the value for the given word
    words[*begin] = count + 1; //increase the count by 1 
    ++begin; //move to next word
 }
mrnutty 761 Senior Poster

It really up to the compiler to decide what to do on overflow. I don't think there is a standard mechanism to handle overflow. But a lot of compilers, wraps around the values.


And it seems like you need a variable that can hold the proper range, promote the variable to the next level and you need not to worry about it. If all the regular data types cannot hold the range that you need, then look into a arbitrary precision library.

mrnutty 761 Senior Poster

>>And of course, is it WORTH passing ints by reference?
No not really, unless you do need to modify the int. Reference and ints usually take up same size, so no noticeable advantage.

mrnutty 761 Senior Poster
foo(Matrix m); //makes a copy
foo(Matrix& m); //does not create a copy but now we are able to change m inside foo
foo(const Matrix m); //makes a copy, not allowed to change inside foo
foo(const Matrix& m); //does not create a copy and cannot change m inside foo

and no noticible performance boost from unsigned versus int. I just hate getting those "Warning: comparing signed and unsigned", so I just make the variable in the loop unsigned by default. If the variable doesn't need to be negative, then just make it unsigned. But making it int is no problem either, in most cases.

mrnutty 761 Senior Poster

>>And @firstPerson, <vector> is a header-only template library, why you bring up the aspect of loading DLLs beats me. This is just a question of include-guards (or header-guards). If you have #include <vector> twice, the only thing that is going to happen at the second #include statement is that the pre-processor will re-open the <vector> header-file, see the include-guard, skip to the end, and no code will be added as a consequence.

Oh ok. I was thinking something else.

mrnutty 761 Senior Poster

>>There is an error concerning lines 10-14. I had been using this code previously without errors. I'm not sure what I may have changed.

IT previously worked because you probably never used that function, so the program didn't instantiate it. But since now you are using it, the compiler instantiates it, and when it does, it sees a weird name called stringstream that it hasn't seen before, because in that file there is no definition or includes that says to the compiler that the weird looking name is defined. So to solve you problem, as suggested, include sstream, and then the compiler will see that the weird looking name has indeed been defined.

mrnutty 761 Senior Poster

Just some few points:

typedef std::vector<double> Vec; //Vector
typedef std::vector<Vec> Mat; //Matrix

Its just preference, but I think its more clearer if you say the full Name, maybe

typedef std::vector<double> RowVector;
typedef std::vector<RowVector> Matrix;

Use const-correctness when you can, for example:

////getColumn////getColumn////getColumn////getColumn////getColumn////getColumn
Vec getCol( Mat x, short b ){ //take's b'th column of x
    Vec y;
    for( short r=0; r<x.size(); ++r ) y.push_back( x[r][b] );
return y;
}

that function doesn't modify matrix x, so make it const Mat& x, remember to use reference when you can so you avoid making unnecessary copies. And there is no advantage of using short, just use int because the compiler might turn it into an int anways. Plus it feels like more convention to use int in loops rather than shorts, not to mention int's range is higher. So the resulting code might look like this:

Vec getColumn(const Mat& matrix,const int columnNumber){ 
 Vec columnVector(matrix.size()); //initialize its size to the amount of row
 for(unsigned row = 0; row < matrix.size(); ++row){
    columnVector[row] = matrix[row][columnNumber];
 }
 return columnVector;
}

In matrix and vector operations, people have all kinds of crazy operators that do different things, and in turn this makes it harder for the users. So Instead of defining a weird operator that isn't really standard, in terms of its use, just create a named function. For example you have,

////transpose////'////transpose////'////transpose////'////transpose////'////transpose////'////transpose////'
Mat operator~( Mat x ){ //transpose
    short n = x[0].size();
        Mat trans(n); // transpose
        for( …
mrnutty 761 Senior Poster

>>Why is it a bad idea to use the std namespace for my new functions? If all of my functions have names which are different than the names of std functions, it is no harm, right?

No do not do that. To avoid conflicts( perhaps in the future), you should strive for modularity. That is, think of namespace std as a unit which is part of the standard library, and now create your own namespace, and think of that as a different unit thats related to your application, and you may possibly have other namespaces from for example 3rd party library, and so you could think of those namespace as a different unit.


>>Also, it is more convenient because I won't have to write std::function every time I want to call a function in my program. (Or if my program uses the standard, I would have to use myname::function every time I want to use a function from my header file.)

What convenient for you might not be convenient for others. When you program you should program it so that it is easy to maintain. Although it might solve your solution right now, would it cause problems later on the road? Is your solution clear and intuitive?

And whats just one more line to solve your program? Don't be lazy, you can easily say using namespace MyOwnNamespace; and go on from there.

mrnutty 761 Senior Poster

Hmm, for me, i'll do it this way.

double max(double a, double b, double c)
    {
    double max=a;
    
    if(b>max)
        max = b;
    if(c>max)
        max = c;
    return max;
    }

It might not be the best solution but i find it easier this way.

Thats the general idea, although it would be more clearer if you overload max for two inputs.

double max(double a, double b){ 
 if(a > b) return a;
 else return b;
}
double max(double a, double b, double c){
 return max( max(a,b) , c );
}
mrnutty 761 Senior Poster

Are you comparing char* to char*? It depends on the datatype of keyword. If so then consider using strcmp function of change from char* to std::string

mrnutty 761 Senior Poster

You can't compare in C++ like you do in math. This if(a > b > c) is wrong, it gets evaluated to (a>b) > c . So if a>b, it returns true, and it compare if true is > c. What you want is if(a > b && b > c) But I suggest something more easier, namely make a max(double a, double b) version. Then use that in max(double a, double b, double c) .

You can use the 2 parameter version in the 3 parameter version by first finding the max of a and b, then using that result to find the max of the result and c, and return that new result.

mrnutty 761 Senior Poster

Steps:

- Get ColumnSize
- Create a 2D array ColumnSize x ColumnSize with each element initialized to ' '(space)
- Populate the First and last column of the 2D array '#'
- for i = ColumnSize - 1 to 0
   - make Array2D[ColumnSize][ColumnSize] = '#'

- Print the whole array

Its more easy to grasp( at least I think so ) if you use the above approach, but using can do this without using array

mrnutty 761 Senior Poster

Presumably I'll have a family by then, So I'll hang around with them, Im a fun guy!!! Other than that, I have no idea, only time will tell

mrnutty 761 Senior Poster

I'm quitting-ish it as well. I disabled viewing my profile by everyone except me. THe only reason I use FB is to see how my friends are doing, and occasionally talk to few of them.

mrnutty 761 Senior Poster

To transverse the tree and test for certain condition you can a structure like this:

//assume private
template<typename Predicate>
bool MyTree::transverse(const TreeNode& root,const Predicate& tester){
  if(!root) return false;
  else if(tester(root.getCod()) == true) return true;
  else return transverse(root.getLeftChild()) || transverse(root.getRightChild());
}
//assume public
bool MyTree::find(const std::string& target){
 struct MyCompare{
   bool operator()(const std::string& val)const{ return val == target; }
 }
 return this->transverse(this->rootNode , MyCompare);
}

The above is to give you an idea, I make no guarantees!

EDIT: It seems like you also want to store the node if there a match, in that case you can simply change a few things like so.

//assume private
template<typename Predicate>
bool MyTree::transverse(const TreeNode& root,const Predicate& tester){
  if(!root) return false;
  else if(tester(root) == true) return true;
  else return transverse(root.getLeftChild()) || transverse(root.getRightChild());
}
//assume public
bool MyTree::find(const std::string& target){
 struct MyCompare{
   TreeNode* matchNode;
   MyCompare(): matchNode(0){}; //init to 'null'
   bool operator()(const TreeNode& node)const{
     bool res = false;
     if(node.getCod() == target){
       matchNode = &node;
       res = true;
     }
     return res;
   }
 }
 MyCompare comp;
 bool found = this->transverse(this->rootNode , comp);
 if(found){
   /* comp.matchNode */ is valid and is the node that matches the target
 }
 else{ 
  /* no match found */
 }
 return somethingDependingOnAbove;
}

Basically when comparing the predicate, if its true you also save a pointer to that node

mrnutty 761 Senior Poster

PLease help me with these questions, I was interviewed for thses just today
Q1)Can we delare constant data members inside a class?
Q2)does friend function violates encapsulation/data hiding?
Q3)what are the types of polymorhphism you know?
Q4)why do you need virtual functions?
Q5)Can we do something like\
int & = NULL;
Q6)what are pragmas.Give an example?
Q7)what are the different ways to acces private members of a class?

1) Yes.
2) No.
3) Function overloading, dynamic ,static
4) For polymorphism
5) No
6) Used to avoid linking a file more than once, non-standard solution
7) If you in the class, and trying to access your private members, you can simply call it by its name, ex runPrivateFoo() or use the this syntax, as in,
this->runPrivateFoo()

mrnutty 761 Senior Poster

Its behavior is equivalent to :

//src via cplusplus.com

template <class InputIterator1, class InputIterator2, class OutputIterator>
  OutputIterator set_difference ( InputIterator1 first1, InputIterator1 last1,
                                  InputIterator2 first2, InputIterator2 last2,
                                  OutputIterator result )
{
  while (first1!=last1 && first2!=last2)
  {
    if (*first1<*first2) *result++ = *first1++;
    else if (*first2<*first1) first2++;
    else { first1++; first2++; }

  }
  return copy(first1,last1,result);
}

Note that the inputs needs to be sorted already. That is for this code set_difference(a.begin(), a.end(), b.begin(), b.end(), result.begin()); the vector 'a' and 'b' needs to be sorted already for the vector 'result' to contain the valid expected results. Other than that, you might just need to read up on the definition of set and its operations.

mrnutty 761 Senior Poster

Why? Sure, you can make it more concise, but it doesn't strike me as cringe worthy.

I guess, since its not really harming anything. But idk why, its just does. Maybe not cringe but more frustrated.

mrnutty 761 Senior Poster

I always chringe when I see a predicate coded like this

bool notWanted( char in )
{
	if( in == ',' || in == '$' )
		return true;
	return false;
}

when it could be more concise

bool notWanted( char in ){
 return in == ',' || in == '$'	
}

or if you have a lot of identifiers:

bool notWanted(char in){
 return std::string(",$abcdegfhijklmnopqrstuvwxyz").find(std::tolower(in)) != std::string::npos;
}
mrnutty 761 Senior Poster

Huh? Oh wait I though he wanted each value separated by ',' into a different value. My mistake then, misread his post.

mrnutty 761 Senior Poster

Here is a complete sample, instead of rolling your own replaceAll use std::replace_if algorithm.

#include <algorithm> //for replace_if algorithm
#include <sstream>  //for stringstream object
#include <cctype> //for isspace function

//function checks is the passed argument is a comma
bool isComma(const char c){ return c == ','; }

int main(){
 //the sample string we are going to demonstrate this demo on
 string sample = "124,567,789.123";

 cout << "Sample string = " << sample << endl;

 //remove all  instance of ',' with ' '
 std::replace_if(sample.begin(),sample.end(),isComma,' ');

 cout << "Adjusted string = " << sample << endl;

 //extract all values into a float from sample string
 stringstream stream( sample ); //give the stream a string to work with
 float val = 0; //holds the value that will be extract into from out 'stream'

 //while there are things left to extract and there is no extraction failure, extract the value in the stream into our variable val
 while( stream >> val ){
  cout << "Extracted value =  " << val << endl;
 }

 return 0;
}
mrnutty 761 Senior Poster

Do something like this:

Assume the user inputs something like this, "234,324,324.66". Then you can do the following,

1) Replace all instance of ',' with ' '. That is replace a comma with space.
2) Load the string into a stringstream object
3) Read the money one by one.
Here is a sample program.

string input =  "234,324,324.66";
input = replaceAll(input,',',' '); //replace all instance of comma with space.
stringstream stream(input);
float val = 0.0f;
//extract value, that is convert the string into a floating value
while(stream >> val){
 cout << val << endl;
}

Note if your input is like this "$234,324,324.66" then you can just remove the '$' and work on from there

mrnutty 761 Senior Poster

Don't know if I agree with the call find( sqrt( value ) , false, NULL , true ) because then isPime will be working with the second root since find calls isPrim on line 73.

The other point you made is great, I'll be sure to implement that. It's gonna save up a lot of memory and CPU power, weird how I didn't do it that way in the first place since that's how you would do it on paper.

If you want to save CPU power, then consider looking at faster algorithms. The prim tester you have runs in n*sqrt(n). To start, have a look at http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes for finding primes.

mrnutty 761 Senior Poster

You can delete line 158 and 193. Also quoted strings i.e "quotedStrings" are automatically null terminated via compiler, so you don't have to manually add null character like you did here "-c\0"

mrnutty 761 Senior Poster

What problem are you having?

mrnutty 761 Senior Poster

Why the pointer in the first place? You could manage without it, can't you?

mrnutty 761 Senior Poster

For you size()const function just return size, no need to check if its equal to 0 or not.

For your peek you should return a constant reference like so :

template<typename Type>
const Type& peek()const{
 return head;
}

and for your dequeue you have a choice, either not return nothing or return the popped element. If you wan to return the popped element then make a copy for the popped element remove the element, and return the copy.

mrnutty 761 Senior Poster

When you enqueue, increase size by one, and when you dequeue decrease size by one. But make sure your adding and removing valid data. So only increase size if you add valid data and decrease size if removing valid size.

mrnutty 761 Senior Poster

Click on the file, hit "Ctrl + C" and goto the location where you want to paste it and hit "Ctrl + V" where the '+' means together or in conjunction.

mrnutty 761 Senior Poster

>>Any linked data structure has that benefit, but it's not the point of linked lists[1]. I'd argue that the point of a linked list is the principle benefit, which would be efficient growth (ie. insertion and deletion) in the absence of random access

I would like to point out one thing, in theory insertion/deletion is constant in a usual linked list implementation, but however one should think about it practically. Since the memory is all over the place in linked list, its not cache friendly, thus causes( or can cause ) a lot more cache misses, which would increase the latency time. Thus when you think you need linked list, you might be able to get away with using an array, especially if the order doesn't matter. If the order doesn't matter then you can achieve constant insertion and deletion with arrays too!! And its cache friendly. But as usual, it all depends. Its just a thought I figure to share.

mrnutty 761 Senior Poster

Let's give it a try:

int x;
x is an int.

int *p;
p is a pointer to int.

int const *p;
p is a pointer to const int.

int const * const p;
p is a const pointer to const int.

Now do the same thing with const to the left and reading left to right:

int x;
int named x.

int *p;
int pointer named p.

const int *p;
const int pointer named p?

const int * const p;
const int pointer that is const named p?

I guess I'm just weird then.

mrnutty 761 Senior Poster

Which goes against the more consistent policy of reading right to left. Both are valid, and since the OP's code used const on the right, I maintained that style.

Really? I thought it was more naturally to read things from left to right?

mrnutty 761 Senior Poster

Make the member function a actual function. If more than one class actually needs it, then its nor correct to make it a member function for one class.

mrnutty 761 Senior Poster

Man you guys are really something. Anyways, I told Mr.X to stop and he gave me his word. So its all peaches and cream

mrnutty 761 Senior Poster

Then the code should look like this:

string const& symbol::at(int index) const {
  assert(index < symbol_data.size());
  return symbol_data.at(index);
}

@OP this might be more clearer:

const string& symbol::at(int index) const {
  assert(index < symbol_data.size());
  return symbol_data.at(index);
}

So you can read it as 'constant string-reference' instead of 'string const-reference'. Both the produces the same result, take your pick.

mrnutty 761 Senior Poster

>>error: ‘template<class _Tp, class _Alloc> class std::vector’ used without template parameters
This error tells you your problem. You are using std::vector without templates. Why are you confused?

mrnutty 761 Senior Poster

For some reason I didn't read the second part of that. Facepalm -__-