StuXYZ 731 Practically a Master Poster

Ok in the first instance, using power is plain ugly and inefficient. The typical route for a polynomial in the positive sense, is to do something like this:

int total(0);
int xpow(1);
for(int i=0;i<=degree;i++)
  {
    total+=coef[i]*xpow;
    xpow*=x;
   }

You can also do it via an internal bracket expansion: [this is effectively (((coef[N]*x+coef[N-1])*x+coef[N-2])*x+.... ))) ]

int total(0);
for(int i=degree;i>0;i--)
  {
    total+=coef[i];
    total*=x;
  }
total+=coef[0];

I like the second one slightly more.... but not alot in it. [Note the fact you are counting down in the loop, AND you cannot save a step by initializing the total to coef[0] before the loop. -- I only emphasize the last point as ran a 2000 CPU hour simulation with that bug in it :(. ]


Your display function is wrong because you write coef[0] twice, run the loop for(int i=1;i<degree;i++) . Note that it is normal to write polynomials high power to constant.

Your multiply: If you want to limit the degree to less than 100, then as well as a warning exit as well. Also have your resized coefs??? in temp do you zero coefs in temp ???

Note: Mike_2000_17 beat me to the post [must learn to type faster], sorry for the repeat, the second version of the evaluation code might be of merit, however.

p.s. Thanks for posting a good first post question to the C++ forum, e.g. code blocks, and sufficient information about your problem and what you have tried.

peterman.k commented: Very helpful +1
StuXYZ 731 Practically a Master Poster

Your biggest problem here is that you (a) are trying to do evergthing at once, (b) cell broad....

You seem to have overlooked that if you have a cell board; in your class definition, then you don't put cell in front of broad to used it. That is because your have already said it is a double array of cells.

e.g.

void minesweeper::displayBoard() 
{
for (int i = 0; i < SIZE; i++)
  for (int j = 0; j < SIZE; j++)
    {
      if (board[i][j].covered == true)
        cout << " ";
      else
        // You need to print something if the cell is NOT covered : 
        cout<<board[i][j].minesAdj;
    }
}

You HAVE to start with something simpler than this because basically, I don't think you understand what a definition is and what a declaration is. Please do something with say a simple class with one integer, and one method, get that to work, and understand how to have 5 different versions.

class A
{  
   int x;
   A();
   void doSomething();
};

int main()
{
   A XX;
   X.doSomething();
   A array[5];
   for(int i=0;i<5;i++)
      array[i].doSomething();
}

Until you are happy with that code, can write a simple constructor and a meaningful doSomething (hopeful, one that writes something out, maybe changes x etc. you are going to struggle.

All coding is about taking small steps to the goal, in your case you have taken one huge step, it is MUCH better to take a step of small steps so that you …

StuXYZ 731 Practically a Master Poster

Not surprising because of a tiny bug in your loop: You wrote: for( int inte = 1; inte = 1; ) { } Now a for loop has four parts, first an initializer, that goes from the first open bracket to the semi-colon. Second a conditional, that goes between the first and second semi colon, Next is post iteration statement, that goes after the second semi-colon. Finally there is the loop block that goes between the two braces { }.

The loop is done this way.
(a) Carry out whatever is in the initialization statement
(b) Test the conditional.
-- If the conditional is FALSE : leave the loop block -- Do nothing more.
-- if the conditional is TRUE : continue to (c)
(c) Execute the loop block.
(d) Execute the loop iteration statement
(e) goto (b).

So in your case:
(a) you create an integer inte. Then it is set to 1.
(b) Determine that inte=1 is TRUE. That is because ALL integer assignments of any value other than 0 are true.
(c) execute loop block
(d) Nothing to do
(e) Go to (b)

Thus you can never get out of your loop. That is why 34/35 dont get run.

Also please please call your variables something slightly more descriptive, using inte, integ intege is asking to make a typo and cause piles of difficulty finding the bug.

StuXYZ 731 Practically a Master Poster

Ok first off, welcome to daniweb, and thank you for writing a clear post with code blocks and not-too much and not too little code!

Ok to your problem, you have unfortunately made a couple of logic errors. First, consider your loop, for(int c=2;c<= num;c++) . This will test each possible factor up and including the number itself. If this was the only error, ALL of your test numbers [except 2] would be reported as not-prime.

Now, let us consider the inner part of the loop, numPrime is set true each and every time round the loop. Then it is set if a factor is found. BUT then it is tested, and regardless if it is either true/false you execute a break statement. Therefore,you only test if the number divides by 2. No other numbers. You can see this if you add a line cout<<"Test number c == "<<c<<endl; as the first instruction of the loop.

So to remedy you could do something like this

numPrime=true;
for(int c=2;c<num;c++)
   {
     if (num % c == 0) 
       {
          numPrime=false;
          break;
       }
   }

  if (numPrime == true) 
    std::cout<<"Number prime"<<std::endl;
  else
    std::cout<<"Number not prime"<<std::endl;

Some simple improvements that will help, you only need to test up to the square root
of the number, since if a*b=N^2 and a=N+x and b=N+y where x, y and >=0 then
a*b== N^2 + N(x+y) +xy. Which can only hold if x,y==0.

StuXYZ 731 Practically a Master Poster

First off C++ has evolved in the last 10 years, hence some changes. These changes were because of unforeseen problems that occurred.

Let us start with why using namespace std; and why you might not want to do that anyway.

What happens in that there are a large number of standard library types, classes and functions that are available via a large number include files. Many of these names are relatively simple, e.g. max, min etc. In the same way that you don't declare everything global, you don't want the who symbol table polluted with names. Therefore, they are put in a namespace (std). That way you can select the symbols you are going to use and not accidentally introduce a "difficult to find" bug by using a global symbol. e.g.

using std::cout;
using std::endl;

Or you can explicitly type the namespace at the point of use, e.g.

std::cout<<"this is a test"<<std::endl;

However, you have the option to go back to the old way, and type using namespace std; . Obviously, you can do the same for all the other namespaces that you import. However, if you get into difficulties by name pollution...sorry you only have yourself to blame. :) [Note for small projects, you will be fine, but bigger projects don't work]. Also note that all the using commands are scoped, so you can have it globally, or just for one section etc. That is why you should not put them in an include file.

StuXYZ 731 Practically a Master Poster

Having looked at Rebellions test case, which is clearly has complex roots, I think that you are going to have to use complex numbers or use two doubles. Since two doubles is a bit ugly let me talk about std::complex<double>.

First of there is an amazing amount of stuff in that type, especially for the beginner. There is a namespace (std) and there is a template class. Both of which deserver a whole chapter in Stroustrup's C++ book!

However, the beauty of C++ is that once you OR someone else, has actually defined a class, complete with all the operators (e.g. +,-,* etc), you can use it almost as if it is a normal type, without worrying about exactly what it is.

So if you did this

// Note: have to convert b*b-4ac to a complex or sqrt(double) will be called.
std::complex<double> sPart=sqrt(std::complex<double>(b*b-4*a*c));
and 
std::complex<double> root1= (-b - sPart)/(2*a); 
std::complex<double> root2= (-b + sPart)/(2*a);

You could then just output your result. e.g. std::cout<<"Root 1 == "<<root1<<std::endl; , or you can check that the solution is a complement
by doing root1*root2, etc.

This may not be what you want, however, you can also solve your problem by noticing that if b*b-4*a*c is less than 0, then that part is the imaginary value, and you can
output it as std::cout<<"Number = "<<-b/(2*a)<<" "<<sqrt(4*a*c-b*b)/(2*a)<<"j"<<std::endl; ;

Finally, If a is zero there is still a solution, since you have b*x+c=0 , i.e x = -c/b.

StuXYZ 731 Practically a Master Poster

Two quick comments, AD is correct that you should have deleted line 4 in Fraction.h, [and that you have misspelled fractions in main()] (what it does is define the symbol hbg_cmpsc122 as and empty value. Therefore when you write namespace hbg_cmpsc122 { you have effectively writen namespace { .

This is why you have all the error messages to the unnamed namespace.

The normal include file guard, is to write this

#ifndef FRACTION_H
#define FRACTION_H

 // your stuff here...

#endif

So perhaps it would be better to change line 4 of Fraction.h to #define FRACTION_H .

Finally, if you want to turn warnings on for g++ then use g++ -W -Wall.

Ancient Dragon commented: Yes, that's what I meant :) +33
StuXYZ 731 Practically a Master Poster

Your problems include two things that come to mine:

(a) the answer that you require is complex, but you are trying to put that into a double. Not going to work. Instead add a #include <complex> to your headers and use std::complex<double> root; . You are also going to have to be careful with your sqrt. Since the incorrect sqrt function (that taking a double) will be called if you don't. [i.e. you want to cast the b*b-4*a*c to a complex before taking the sqrt. ]

(b) Your test for zero is strange, what is wrong with this quadratic x^2-9=0 ??
[Small reminder, testing doubles as a==0 is often not going to go well, as you are likely to have a very small number not zero]. Anyway, you only have to check is a is not too small to cause an overflow. That is a better test done after the calculation.

StuXYZ 731 Practically a Master Poster

Sorry, as I was reviewing my post, I then had a big edit of it... then I spotted the error....

Line 78 is fine, it was me miss reading the variable name. [Sorry for the confusion]

StuXYZ 731 Practically a Master Poster

Introductory Note: You have not written std::vector<double*> S; . Which is a completely different discussion. This is often frowned on because it is SO easy to mess up, the memory [de]allocations.


Ok: In the general sense it is perfectly fine to have a point to a vector, or any other stl class. There are several "obvious" reasons for having a pointer, e.g.
(a) you could have extended a standard class and have a polymorphic system.
(b) you have a selection of classes and were avoiding a bit of memory/resource etc.
(c) You want to transfer ownership of the pointer between objects.

Of those I think (a) and (b) are not good reasons:
(a) isn't good, since the lack of virtual functions in the STL implementations don't make them easy classes to extend.
(b) The size of the class is minimal relative to a filled class. Normally has zero bearing on memory footprint etc.
(c) I am kind of ok with, but I would normally wrap it in another class, with better control and semantics.

Now let us look at what you are actually doing and see if I agree.

Well every student has a vector<double> assignment, so you are only interesting in option (c). Indeed this does make your sort quicker. However, the cost is the potential bugs that you will introduce.
However you can effectively have what you want (and slightly more optimization), by moving the …

gerard4143 commented: Great pointers +4
StuXYZ 731 Practically a Master Poster

The A and the B are the two different RectStruct that you are comparing. If you don't pass that then there is no point to the function?

The function takes any two rectangles and returns (in variables min/max) the areas such that the largest area is in max and the smallest area is in min.

StuXYZ 731 Practically a Master Poster

Well if your professor said use a struct, not a problem you just do this:

struct Rect
{
  private:
     float x;
     float y;
     // etc
  public:
    Rect(const float,const float,const float,const float);
};

Yes I know that is not what was intended ;)

The only difference between a struct and a class is that a class is by default private and a struct is by default public. If you add private: and public: statements they are the same.

Three minor points, the typedef serves no purpose but to give you two names for the struct, e.g. Rect and RectStruct, surely just call the struct RectStruct.

You might want to consider using a reference to RectStruct in printRectValue/assignRectValue/calcRectArea etc, e.g. float calcRectArea(const RectStruct&);

NEVER put using namespace std; at the end of an include file like that!!

StuXYZ 731 Practically a Master Poster

First off you haven't give us Rect.h, and that is important.

However, guessing that Rect.h looks something like this

struct RectStruct
{
  float x;
  float y;
  float height;
  float width;
};

First off, I really like what you are trying to do with this code, you have almost all the main aspects of basic functions in this code. Sure, it is not correct, but once you are finished, you effectively have a single example, which covers are large number of techniques. Additionally, you have a lot of output, that is a really good debugging/understanding tool.

However, we have a few problems to discuss:

Firstly, you have decided to make RectStruct a simple structure, but then added a whole host of assignment and calculation functions. That is ok, but think about if a class with public methods and private data would have been better.

Second, calcMinMaxValue, is a truely horrible function. The reason is that you
allocate new memory to rect01, then don't delete it. You seem to be using rect01
and rect03 without any initialization. [or did you ad a special default constructor
to RectStruct in Rect.h??]

So calcMinMaxValue function should be like this:

void calcMinMaxValue(RectStruct& A,RectStruct& B,float& min,float& max)
{
   // your stuff here
}

Thirdly, int main(), you allocate two rectangles rect01 and rect02. That is fine,but for every new there should be a delete e.g. put a delete rect01; etc at the end of the code.

StuXYZ 731 Practically a Master Poster

Your problem is a combination of reverse and the way you call reverse.

You have reverse (char*), as taking a char pointer. That is an area of memory that can be modified. However, when you call it, you pass a constant string. C++ represent that memory as non-mutable, i.e. It does not allow you to modify it. Hence you get a runtime error.

So to fix your problem call reverse this way

int main()
{
   char word[]="university";
   reverse(word);
   // NOTE: word has changed.
   std::cout<<"Word is now ::"<<word<<std::endl;
   return 0;
}

Additionally, main() is actually returns an int, most compilers that were written in this century, will not allow you to compile it as a void. [Which tell us that you really should get a new compiler. There are many good free compilers and IDE (Integrated development environments), available.]

StuXYZ 731 Practically a Master Poster

Not 100% sure what you are after, so I am going to re-iterate your problem as I see it then you can correct me and (hopefully) we can all get closer to the exact problem you are after:

You seem to have several problems that need to be separated out.

(a) You have an array of detectors that are silicon based. The array is a close packed structure on a rectangular/square array (?) [This is important -- is it square/rectangular -- since that effects the probability that charge can move to the next cell]

(b) the readout electronics is obviously not reading in the same pattern, [thus allowing electronic cross talk to be seen -- this is different from pixel cross talk, and to improve deadtime issues]. Thus the array of data that you get needs to be re-mapped to find out which pixel is next to which other pixel.

(c) The data you get for a given pixel is simple binary detection of an event/ no detection. There is no time information, no charge information etc. (?)

(d) As I understand it you you have a grid of pixels in space, that have a finer grid of position sensitive points within each grid point. You seem to have 2048 pixels each made up of 16x16 fine grid of points.

(e) There is charge spillage from a fine point to its nearest neighbours but there is no charge spillage to the next pixel grid …

StuXYZ 731 Practically a Master Poster

Sorry but I REALLY don't understand what you are trying to do. I would appreciate an example or two. However, that leaves the code, which is simply horrible. It cannot possible be necessary to write so much code to do this, and it cannot be necessary to using strings to manipulate the data form [They are very very expensive (CPU/memory etc) for the purpose of bit operations].

So I am posting a simple reverse bit code that reverses the bits in an integer. If you then want to apply xor or and etc to it. Then just do a reverseBit(45) ^ 1202; or whatever you wish to do.

If you can post a short description of what the code is trying to achieve, I/others may be able to help you further.

#include <string>   
#include <iostream>

std::string
convertToBinStr(unsigned long int V)
  /*!
    Simple function to convert an integer
    to a binary string
  */
{
  std::string Out;
  int sIndex(sizeof(V));
  Out.resize(sIndex);

  while(V)
    {
      sIndex--;
      Out[sIndex]=(V & 1) ? '1' : '0';
      V>>=1;
    }
  return Out.substr(sIndex);
}

unsigned long int
reverseBits(unsigned long int V)
{
  unsigned long int  result(0);

  for(int i=0;i<sizeof(V);i++)
    {
      result <<= 1;
      result += (V & 1);
      V>>=1;
    }
  return result;
}

int main()   
{   
  std::cout << std::endl;
  std::cout << ((12+20) & 1456) << std::endl;
  std::cout << "Convert == "<<convertToBinStr((12+20) & 1456)<<std::endl;
  std::cout << "Convert == "<<convertToBinStr(reverseBits(32))<<std::endl;
  return 0;
}

p.s. I simplified your includes, main() returns an integer, and I disposed of the system calls.

StuXYZ 731 Practically a Master Poster

Sorry firstPerson, I think I miss-read what you were saying and then failed to explain my comment.
The code as presented can allow gcd [the variable] to be zero. [hence the test in the code, etc].

I fully accept that nobody should start with zero (or one) but most likely from 2 and go up.
And you are correct that gcd cannot be zero.

I also think that this reduction method should be deleted and re-written using a better algorithm.

Anyway, sorry to all those I confused. I think my original post is mostly sane after that statement... (hopefully) .

StuXYZ 731 Practically a Master Poster

First off the most scary thing that I see is the global variables defined just below your line using namespace std;. Arrrhh.... don't do this, they are not needed.

Next reduction is missing a few brackets.

Yes gcd CAN be zero if say numerator and denominator are 1.

Now the algorithm used is a mess. It is easier to count up, than down.
You will not found a common factor that is bigger than the SMALLEST of the
numerator and denominator, e.g. 1/387642212 is not going to be reduced
regardless of the factors in the denominator.

So the algorithm you need:

Loop I: from 2 to smallest number
    while (I is common factor)
        divided denominator and numerator
    recalc smallest number

Note: It is very important to check a factor many times, e.g. consider 16/32,
2 is a factor but you can divide by 2, four times.

Improvements of this algorithm include : using a prime sieve, so you only have
to test primes, stepping up in 2s, looping to the sqrt(smallest) , but remembering
to test the smallest number as well.

StuXYZ 731 Practically a Master Poster

You are indeed correct things are not working correctly:

You problem is simple, you have forgotten to use a virtual destructor in baseClass.

All you have to do is add virtual baseClass() {} to your baseClass
and it will work.

However, please add virtual to your destructors of both your other classes. The general rule is ALWAYS add a virtual destructor if you have virtual functions of any sort. Otherwise you will have problems like this. [Most compilers warn you of this problem if you enable warnings]

StuXYZ 731 Practically a Master Poster

The problem may be that you have forgotten to remove the skipws (skip white space) flag from the stream. e.g.

std::cin.unsetf(std::ios::skipws);

If that is the case, then please also remember to return the stream to the state
you had previously. This is facilitated by setf() and unsetf() because both return
the state of the flags before the call e..g

std::ios::fmtflags flagIO=std::cin.unsetf(std::ios::skipws);
StuXYZ 731 Practically a Master Poster

The problem is your copy constructor, for client.

So let us see how we get to that :
Line 5 of youf first program uses this: vektori.push_back(Client(account, firstName, lastName, balance)); This constructs a client object and copies it into the vector. With this line
you also call Client(const Client&); .

At this point you have a probelm: your Copy constructor is this

Client::Client(const Client& client) {};
// This does NOT copy the account number / the strings etc

Try writing this instead:

Client::Client(const Client& client) : 
   account(client.account),firstName(client.firstName),
   lastName(client.lastName),balance(client.balance)
{
   std::cout<<"Confirmation that copy constructor called"<<std::endl;
}

I would STRONGLY recommend adding an assignment operator. If you do not the compiler will add one for your AND because you are using string it will be 100% certain to be wrong [std::string allocates memory]. Always add a assignment operator unless you are 100% certain about not needing it. [Most of the time just add it anyway.]

It would be something like this:

Client&
Client::operator=(const Client& C)
{
   if( this!= &C)
     {
       account=C.account;
       firstName=C.firstName;
       lastName=C.lastName;
       balance=C.balance;
     }
    return *this;
}

p.s. That is an extremely well set out first post. Clear as to the problem, sufficient code to replicate the problem, but not excessive, and uses code tags. Thanks!

StuXYZ 731 Practically a Master Poster

Your problem looks like a lack of an extern + a scope error

Let me explain. You seem to "effectively" want to do this

int main()
{
   int var(10);          // this variable is local to main NOT the program
}

void foo()
{
   int a=var;         // THIS will not compile.
}

This is not allowed. That is because main(), as will all funcitons, protects its scope. So how to get round the problem:

int var;    // NOTE ABOVE MAIN

int main()
{  
   var=10;
}

void foo()
{
   int a=var;     // THIS is ok IF foo()'s defining is in the SAME file as main.
}

Well what if you want to have two separate files : For that we need the extern keyword.

// File Main
void foo();  // declaration 
int var;

int main()
{
   var =10;
   foo();
}
// SECOND FILE
extern int var;          // Note the extern keyword.

void foo()
{  
   int a=var;           // this is now ok and will get the value 10.
}

Hope that helps and question/comment please ask

Ancient Dragon commented: well said +31
StuXYZ 731 Practically a Master Poster

If the output is to the console/terminal. The you can do this

./program input_data > outputFile.txt 2> errorFile.txt

Note that I created and output file for the normal output and an error txt file for errors. You might want to put them all together with

./program input_data > outputFile.txt 2>&1

which just means put the output to outputFile.txt and then write the errors to the same place as the standard output.

Note that works on bash shells [default for ubuntu and most other linux distributions]


---------

Note if you actually want to pass the output to a file and process the data, you can pipe it and
use popen and associated pipes. You will need to include the unistd.h file and you can create a
file pipe e.g.

FILE* inputPipe;
 
inputPipe=popen("myProgram","r");

if (inputPipe == NULL)
   { // Deal with error }

char txt[MAXCHAR];
while (fgets(txt, MAXCHAR, inputPipe) != NULL)
   {
      std::cout<<"Data == "<<txt<<std::endl;
   }

There are more C++ ways to do this with boost and others.. but I am sorry I rarely do that so you will have to wait for a more experienced member to help you [and me] out.

StuXYZ 731 Practically a Master Poster

Sorry but there is insufficient code here to run, test and generally play with,
a bit more of a working example, e.g. something which runs would have been good.

But there are several things that might be a problem:

(a) Given the lines a=(s_axis_1+15)*10; and the similar one for b, did you really mean this. As s_axis is likely to between
-150 and 150 so a is going to be about 1650. Do you have an array overrun??

(b) Did you intend to do the same thing with b, it seems like the *10 was when the data was a flat single array, and you might have been doing int index= a+b; (c) This code doesn't seem to be right: (s_axis_1== -3.65541E-14) . It makes absolutely no difference in the present code (since you cast a to an integer) and any program that uses double precision should not expect zero to be exactly zero, rounding error is a fact of computing.


If you still have a problem can you make the smallest possible test program, even
if you use stuff like double s_axis_1=3.132e3; as the set up etc.
It will help us help you

StuXYZ 731 Practically a Master Poster

Very Very likely!!!! - Never Never in use the default copy constructor unless you are 100% certain about what it does!! Even then don't rely on it!

StuXYZ 731 Practically a Master Poster

Linkage errors:

Basically a compiler has several roles, that use to be done by different programs on the system [And under the covers, still are].

First the compiler turns your code into object code, this is basically assembler but without the correct calls to external data and functions.

Second the compiler then from a set of different object code, joins up these external calls. This is called linking.

You are using a Makefile. That is a method to avoid compiling all of the pieces of the code, if you only make a change in one part of the code. e.g. if you change your quaternion.cpp, then type make, I expect only quaternion to be compiled before linking. It will not compile Vector3.

However, if you change Vector3.h, then I expect Vector3.cpp to be recompiled, BUT if the makefile is written poorly, then Vector3.cpp might not get compiled and if Vector3.h has not changed much the program will successfully link and can be executed. HOWEVER at this point the memory to all Vector3 can be corrupt. That is linkage error. You can check it by deleting ALL of your .o files and re-making.
If the executable is different in any way from the original [before the deletion -- copy the original to a new filename, rm *.o */*.o, make, diff oldProg Prog ], you have a poor makefile, and linkage errors.

Note that linkage errors can also happen if you change a file that …

StuXYZ 731 Practically a Master Poster

Excizted:

Z term zero:

Sorry, some of my posts were a little confused since i incorrectly read the line in the debugger output. My mistake.

From your code, we are left with an error (or failure to write) a copy constructor
in Vector3, or linkage error. Since you by now have done a rm *.o/make clean or whatever, we are left with the Vector3 copy constructor.

By the way does this work:

Vector3 A(-1,2,3);
Vector3 B(A);
std::cout<<"B == "<<B<<std::endl;
StuXYZ 731 Practically a Master Poster

Finally.... (I hope),

The rotation about the axis is better done this way.

Vector3
Quaternion::rotate(const Vector3& v) const
{
  Quaternion qV(0.0,v);   // Set the w part to 0, and the x,y,z to the vector v
  Quaternion RV=(*this) * RV* this->inverse();   // inverse: return the quaterion: w,(-x,-y,-z)
  return Vector3(RV.x,RV.y,RV.z);
}

The main reason for this is numerical accuracy. Note your input (for a rotation) is already out by 1e-4.

StuXYZ 731 Practically a Master Poster

firstperson:

No, it will call the copy construct since your are declaring the vector3 at that point. If you write this:

class AXX {
public:

  AXX() { std::cout<<"Constructor"<<std::endl; }
  AXX(const AXX&) { std::cout<<"Copy Constructor"<<std::endl;}
  AXX& operator=(const AXX& A) { std::cout<<"Assignment"<<std::endl; }
};

int main()
{
  AXX alpha;
  AXX beta=alpha
  alpha=beta;
}

And you get Constructor : Copy : Assignment .

Excizted commented: Thank you for helping and keep doing it. :) +1
StuXYZ 731 Practically a Master Poster

I am going to take a long long short here as to what is wrong;

You write

class Vector3
{
float y, z, x;
};

Note the order!! That worries me (slightly) since you are doing a copy construction
e.g. your line result=pre_result; will actually call the copy constructor and not the assignment operator (operator=).
The rule is that the components are initialized in order. Do you have some test that involves x,y,z in that order [e.g. a making the vector a unit vector etc.],

By this I means this doesn't work:

// WRONG:
Vector3(const Vector3& A) : x(A.x),y(A.y),z(A.z/sqrt(x*x+y*y))
{}

Gives junk result, since the order of initialization is y,z,x [in your case]

Addition to that I have you done a make clean . That is remade your vector class. Is it possible that you have missed the Vector3.h dependency from the Vector3.o in the Makefile. Then you have changed the order of x,y,z and then you get junk. If you delete all the .o files and remake, and it works you have just to find the dependency failure in your Makefile.

If you are using g++, you are using -Wall and you treat each warning as an error.

Finally, since you have a Vector3, why no create the quaternion with the Vector3 + W.

class Quaternion
{
  double w;
  Vector3 Qvec;
  public:
   // ..... 
};

Note that I have made your quaternion a double since any real use with …

StuXYZ 731 Practically a Master Poster

Considering Nathans code: using int i.

Please don't use an int like this, input.size() is normally long int. You (a) should get a nasty warning. (b) it is an input dependent bug.. they are the worst kind so please code defensively for it.

StuXYZ 731 Practically a Master Poster

You should get an error with that code [Nathan's] since size_t is normally unsigned.
That means is it is always >0. Use a long int and a cast. Alternatively use an iterator.

You can also offset by one

for(size_t i=input.size();i;i--)
   temp+=input[i-1];

But I prefer iterators.

StuXYZ 731 Practically a Master Poster

First off as Fbody points out correctly, you ideally will give us a bit more information particularly on dataStructure.

Second, a large number of "memory" errors come about because of memory freed too early. BUT the error only occurs after the memory is used for something else. This may be why is it only happening when you break the program up, because the compiler puts the memory in a different location, which then gets over written. Use a memory debugger, e.g. valgrind. http://valgrind.org and it will tell you the location. It will also tell you if you overrun an array boundary etc.

However, all of this is conjecture/guess work. So please post dataStructure, then we can try to solve the problem.

StuXYZ 731 Practically a Master Poster

Group of death is directly dependent on the host nation, it would not be if the host
nation didn't get put as the first team in the A group.

If the host nation is a cat 3 team, no cat 3 team can play each other, but if the
host nation is say a 1, then two things happen, a single 3 is going to either met the
host nation or one of the other 3s.

In re-thinking about the problem, I think that the deathGroup conditional is wrong.

I define a deathGroup in which more than 2 teams of quality >=2 exist in the group
e.g. 2220 is a death group but 3311 is not, since both 3's will advance but in the
first group a top 16 team will fail, (without playing below par).

So how to code that: simple add up the number of the higher teams:

for(int i = 0; i < 1000000; i++)
    {
      // randomize team rankings which are between 0 and 3
      random_shuffle(group.begin(), group.begin()+24);
      int index(0);
      for(int j = 0; j < 8; j++)  // number of groups
        {
	  int groupTotal = (group[24+j]>1);
	  for(int k = 0; k < 3;index++, k++)  // number of teams
	    groupTotal+=(group[index]>1);
	  
	  if(groupTotal > 2)  // threshold for group of death
            {
	      deathGroup++;
	      break;
            }
        }
    }

Note that care has to be taken with the inital setting of box to have the correct
value for the host.

StuXYZ 731 Practically a Master Poster

Just looked up how the world cup seeding works: It is actually that the top 7 nations + the hosts are seeded to avoid each other. So you have a situation were the sides with difficulty 3 are places into there own groups and then the others are seeded into the groups.

In that case the probability dependent on the host strength:
Host ==3 : 21%.
Host ==2 : 37%
Host ==1 : 44%
host ==0 : 46%

Interesting problem !

So given that SA are not exactly good, e.g. maybe 1, then we had a 44% chance of a group of death.

In the case that the host is a

StuXYZ 731 Practically a Master Poster

This has tow issues : (a) the code (b) your expectations of the output.

First the code:

Since you are re-shuffling the code each time, you don't need to re-assign the groups,
just re-shuffle.
It is much quicker to do it this way:

for(int i = 0; i < 10000; i++)
    {
      // randomize team rankings which are between 0 and 3
      random_shuffle(group.begin(), group.end());
      int index(0);
      for(int j = 0; j < 8; j++)  // number of groups
        {
	  groupTotal = 0;
	  for(int k = 0; k < 4;index++, k++)  // number of teams
            {
	      groupTotal+=group[index];
            }
	  if(groupTotal > 8)  // threshold for group of death
            {
	      deathGroup++;
            }
        }
    }

(b) Now there is a problem, you are adding an extra group of deathGroup for EACH group of death that is found, ie. you test 10000 * 8 groups and find about 10000 groups of death. THAT does not test the hypothesis. You want to test if there are any groups of death within a particular set of eight. It doesn't matter if there are two/three etc in a particular world cup grouping.

So we add a break; after the deathGroup++ line. Then the number is
near the correct answer of about 75%. i.e. there is a group of death in 3 out of 4 world cups.

StuXYZ 731 Practically a Master Poster

Ok well here goes 101 of code compilation on Linux with g++/gcc.

This is simplified from the actual process so after you understand this, there is another level of detail to see.

Basically you can think of code compilation in two stages:

(a) Producing an object file, that is taking your c++ code and turning each of your statements into machine code.

Before I go on, let me discuss that a bit. In your code if you write double a(1.5); a+=1.3; , the compiler (g++) can do this it reserves
a memory location for a, puts 1.5 in it, and the adds 1.3 to it. It writes this in the form of machine code. You can see the direct assembler that it corresponds to by
compiling your program with -S, but this will have a lot of other instructions in the code, but you can find your code.

However, what happens if you write this

#include <cmath>

double func(const double A)
{
 return 2*sin(A);
}

Now the sin function is only declared in <cmath>. You do not have its definition, so the compiler has to put a function call into the assembler, but it doesn't yet know what the definition of that call is.

(b) Now after the source code has been converted to objects, the compiler <em>links</em>
the code together. This is done by ordering the source code AND by ensuring that the links to functions declared in other …

jonsca commented: Always solid answers +4
miturian commented: very helpful (and friendly!) +1
StuXYZ 731 Practically a Master Poster

You have forgotten to add a -lgsl .

That assumes that you want to make a shared library version of your code,
and that you have a path to the libgsl.so file [defined in: ld.so.conf].

IF that doesn't work but you have libgsl.so then you can set the path explicitly e.g.
if the file is in /home/userName/lib g++ -Wall -I /usr/include/gsl -L/home/userName/lib -lgsl -o main.exe main.cpp Finally: Can I say (a) it is "non-unix-like" to use main.exe, normally, just a name, e.g main. Almost all the programs on your linux box are without the .exe. e.g. emacs, vim, ls etc. (b) I assume that you know how to compile the program to object code, and link separately:

g++ -c -I/usr/include/gsl main.cpp
g++ -c -I/usr/include/gsl extraFunc.cpp
// Then the link:
g++ -o testProg main.o extraFunc.o -lgsl

This way your code can be split up etc, and you can reduce compile time dramatically, especially when making small adjustments to a big code.
Hope that helps.

StuXYZ 731 Practically a Master Poster

Try using a string stream:

std::ostringstream cx;

for(int i=1;i<10;i++)
{
  cx.str("");            // clear the stringstream
  cx<<"File"<<i<<".txt";
  std::string Filename=cx.str();
}

Obviously you have to do something with Filename but it has the basics.
Note that since I use a loop, you have to clear the stringstream on each pass.
[you can define the stringstream within the loop if you like].

Cowbox commented: The help worked, until the next error I faced :( :D +0
StuXYZ 731 Practically a Master Poster

First off: Well done of writing your first "big" class.

I have quick question, does the prime check work. E.g what if you have 3, which is prime? I think it give false which is wrong. Also you only need to test as far as the sqrt(N).

pow does not correctly handle negative exponents.

operator%=, operator*= etc normally return a self reference. E.g. Number&.

You might want to think about moving the base of the system from 10, which really under-uses the integer storage space, to something a lot bigger.


I would also like to comment that normally, operator< and operator> etc are implemented with reference to each other, that cuts down the amount of code drastically. E.g.

bool
Number::operator<=(const Number& A) const
{
   // I like this form: 
   return !(this->operator>(A));
  
   // You can write this as well
   return A > *this;
}

Overall, a good first try. IMHO numerical code is one of the most difficult areas since it has to be both efficient and absolutely correct in for an infinite set of inputs. Even if you limit yourself to a basic set of numbers [i.e. 0,1,large,infinity] and their negatives you have a test suite of some >300 tests.

Finally, the warnings are because you are doing this: for(int i=0;i<data.size();i++) . The compiler is 100% correct, if the size of data exceeds the storage of an integer then that is a runtime bug and infinite loop. It can fixed by …

StuXYZ 731 Practically a Master Poster

You could skip the call to the function and just write this

std::cout<<"Time taken == "<<static_cast<double(t2-t2)/CLOCKS_PER_SEC;

You could wrap the static part in a funcit

StuXYZ 731 Practically a Master Poster

The general way to solve N equations of N unknows of ANY powers (e.g. x^5) is the use Bezout's method.
See:

http://www.mathpages.com/home/kmath544/kmath544.htm

(Also there is a lot of literature to improve the speed and numerical stability).

The method is highly tractable to code because as matrix is created and used to reduce the equations down one by one and reducing the number of variables one by one.

At the end of the method you are left with one polynomial in one which you solve by your favorite solving method [eg. the gnu scientific library : http://www.gnu.org/software/gsl/

The resultant polynomial can be of a relative high power, e.g three quadratics in three unknowns will result in a 16th order poynominal.

jonsca commented: Best suggestion +2
StuXYZ 731 Practically a Master Poster

The problem that you have is understanding how the ordering works.
(It is like the maths problems of multiply before addition. e.g 6*5+3 is 33 not 48 )

You have written

if (s[i] == 'a'||'A'||'e'||'E'||'i'||'I'||'o'||'O'||'u'||'U')

which is the same as

if ((s[i]=='a') || true || true || true)

Since each character ('A', 'O' ... ) is not zero, they each evaluate to true.
Thus it is very very unlikely to do what you think it does.

StuXYZ 731 Practically a Master Poster

The obvious errors are things like :

In

int stepOne(Graph &g, ListCell* l, int u)
{
int lowestVert = l->next->adjVertex;  // Seg fault here if l is null
double lowestWt = l->next->weight
stepOneHelper(g,u);
// THIS test is too late.
if(l == NULL)
{
return lowestVert;
}

Also

void stepOneHelper(Graph &g, int u)
{
  // NO Test : u can be bigger than the number of info points in g.
  // e.g u > numVertex.
  if(g.info[u].cell != NULL)
   {
     g.info[u].s = Pending;
   }
}

Seg faults are relatively easy to find were they came from. Just run with the debugger unit it crashes. [If on linux use ddd and then after the crash step up until you reach your code and see what the variables are.]

StuXYZ 731 Practically a Master Poster

I understand for quick solutions you would follow AncientDragon's sage advice.
However, that always leaves a sour taste since I am sure your want to know how to do it:

So here goes

template<typename A>
struct printFunctor
{
   static void print(FILE*,const T& Obj) { }
};

template<>
struct printFunctor<int>
{
    static void print(FILE* fptr,const int& Obj) {  // stuff for int }
};
// and so on for each type

Then it is just printFunctor<T>::print(Fdata,image->m[v][u]); assuming that template object T exists, or you can write printFunctor<int>::print(Fdata,image->m[v][u]); as appropiate.

There are lots and lots and lots of cool variants of this principle.

ylchen commented: Thanks for the solution. +1
StuXYZ 731 Practically a Master Poster

I think that you have got confused with the syntax of declaration and implementation. So here is an example with most of the common things you will likely need. [Please ask if I have missed something]

class Non_Template
{
  // stuff here
public:

  // Class DEFINITION
  template<typename T>
  class some_Template
    {
    public:
       
      T obj;
      
      void setObj(const T&);
   };

  // Two diferent uses of the template
  some_Template<int> IObj; 
  some_Template<double> DObj;
  
};

// Declartion of a member function outside of the class  
template<class T> 
void Non_Template::some_Template<T>::setObj(const T& A)
{
  obj=A;
  return;
}

int
main()
{
  Non_Template X;
  X.DObj.setObj(4.5);    // accessing the member via the class
}

Note I made the template declaration AND the objects public, that was not necessary so change as you wish.

StuXYZ 731 Practically a Master Poster

I agree with Jonsa's point you can put using std::cout; etc, although it is important to remember that they can be put within a scope, e.g. in a function and not the global scope.

C++ is a language that seems to deplore sloppy practice, so in almost all cases always default to more rigor. E.g. if you always define a copy constructor and assignment operator and destructor, your are going to be ok, or if you always make the destructor virtual if you have a virtual function. These are all not necessary but get one of those wrong will cost you a lot of time in debugging.

So if you are beginning don't take short cuts, it will not save time

StuXYZ 731 Practically a Master Poster

I am using namespace along with #include <fstream> in order to use both cout and fout as that is part of the assignment.

Well DONT use using namespace std; You can write it like this:

std::ofstream File("Output.txt")
File<<"This is to the file"<<std::endl;
std::cout<<"Written line to the output file"<<std::endl;

Namespaces are there to avoid global name pollution. You have no idea how many names are in namespace std, it is lots. So don't pollute you program with them, because when you get it wrong the compile error messages are simple incomprehensible.

StuXYZ 731 Practically a Master Poster

First: USE CODE TAGS

Second: you don't not have to declare the variable name in definitions e.g. void resultsfn(int& A); is the same as void resultsfn(int&); .
This often makes code clearer

Three: Dont use

system("pause");

.

Four: You use references BUT the fail to use references in namefn for example. namefn is equivilent to reading two names from the keyboard and discarding them.

Five: You declare resultsfn with SO many variables I can't be bothered to count them. BUT you call it with only 5. That is an error. You need to call it with exactly the number of variables that you declared it with unless you use default values. You are missing all the integers from the end.

Six: Don't use using namespace std; . What is the point of a namespace if you just ignore it. The namespace is to avoid mistypes with short names e.g. cout, ios, string, and others.

Seven: Don't use variable names that a single character away from another variable name. E.g Dont use fout in function outputfn since you have cout. That is asking for trouble .

Eight If you want to writ to a file then open the file first e.g. std::ofstream fileOut(fname.c_str()); Nine: Correct all the warnings

Ten You have an a comma between float and progavg in function outputfn.

Eleven: declaration and implementation signature of outputfn are not the same.

Think that is about it. After …

StuXYZ 731 Practically a Master Poster

The bovious thing to do is to run it in the debugger e.g. gdb or ddd
Compile with g++ -g -o Prog prog.cpp, and the run as ddd Prog . When it hits the seg-fault, use up until you see the problem (backtrace in gdb). It is likely that the fault is say in a sta

There is also another method that is much more rigerous, that is to use valgrind http://valgrind.org/. [Don't think this works on linux] But run your program with valgrind Prog and you get a long list of the memory you accessed without initializing and memory that you didn't free.