StuXYZ 731 Practically a Master Poster

Ok this code made me laugh -- I had better explain.

So let us consider each line in turn [note i have expanded the formatting]

for(int=2;i<1000;i++)         // Simple loop
   {
      for(j=2;i/j;j++)        // Loop to do j=2 to j < i : it works because
                              // integer arithmetic is being used

The i/j uses the fact that integer division ignores the division remainder,
e.g. 5/2 == 1 but 3/4 ==0 . Just writing i/j also uses the fact that any integer other than 0 is true.

To see the effect of i/j consider this

i  j   i/j  
8  1    8     
8  2    4     
8  3    2     
8  4    2
8  5    1
8  6    1
8  7    1
8  8    1
8  9    0

Continuing

// continued from above:
if (!(i%j)) break;           // if j is a factor of i , exit the inner (j) loop.
if (j>(i/j))                 // Test to see if all possibilities for have been 
                             // used since you don't need to test beyond sqrt(i) 
                             // Anything beyond that means it must be a prime

Note that (j>(i/j)) is a way of saying j*j>i . I think that latter is clearer

Hope that helps...

I guess I was more surprised by the way the whole code was written in a divisional style.

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

The obvious thing do here seems to be to use a typedef.

Consider this

class SSE2Vector
{
   // Stuff here that makes use of SSE2 and is fast
};

class BasicVector
{
   // General version. Work on everything.
};

typedef BasicVector Vector;

What you have done there is selected the basicVector for the Vector and you can select the other if you wish. Then you program with just Vector.

However, this is the quick and dirty version. Problems that you have to overcome and CAN be overcome with template metaprogramming or simple #defines are that you don't want to compile the SSE2 version unless your compiler supports it.

Note: if you use templates, what you are going to do is encapsulate the typedef within a structure. However, I will expand of this after you get a bit of experienced with the basic concepts.

StuXYZ 731 Practically a Master Poster

Can you post the compiler error, if you use -llua to link to the library then you need
to have the liblua.so available. Are youg getting the same error message as before?

Also you can't compile this gcc -llua code.cpp, it has to be g++ -llua code.cpp because you will miss other dependencies.

While you are checking things what version of liblua.so do you have, i.e what does liblua.so point to [it will be a symbolic link]

Finally, it is possible to be wrongly linking against different version to the version that is being included. If you have that possibility, then it can be tested by doing this: g++ code.cpp /usr/lib64/liblua.so were you have explicitly said which file you are going to link against. [note there is no -l in this method as you are directly linking].
You can find the liblua.so with the locate command.

If the problem is that you have two version of the liblua.so then you need to either remove one, or re-arrange your ld.so.conf file (normally in /etc/ld.so.conf) so that you get the correct version first, or use an explicit -L path e.g. -L/usr/lib64

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

If you are going to use a C library in C++, you need to compile the headers in C
style. That is done like this:

#include <iostream>
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}

int main()
{
    int s=0;
    lua_State *L = lua_open();
    // load the libs
    luaL_openlibs(L);
    //run a Lua scrip here
    luaL_dofile(L,"test.lua");
    lua_close(L);
    return 0;
}

To compile and built it use: g++ test.cpp -llua You may need to add a -I flag to point to the lua include directories and -L flag to point to your liblua.so library. [In your case, your lua files are in /usr/include and /usr/lib so it is highly unlikely that you will need the -I and -L flags]

StuXYZ 731 Practically a Master Poster

The code as posted works find. [assuming that you put a using namespace std;

There are two possible reasons that you are not seeing this code working.

(a) you haven't actually run THIS code. The error with the lack of std::, includes and
using namespace std; indicate that.

(b) You have strange file permissions, and you write the file BUT second time you cannot overwrite the file. To test that change the text, or put a test into the code to see if outfile is good. e.g. if (outfile.good()) std::cout<<"File good"<<std::endl; Note: try adding an extra line to the output , very very often people forget the last std::endl and also try putting the number output before the test string, and always change the txt string at each test.

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

Ok the problem is one and only one line.

The first is that you are compiling -O3 ... until you have got all the compilation errors out and debugged it DONT use -O anything!

Second the error is on line 428

<< "After Motor voltage: " << d.amv[x]
	       << std::endl
	       << "Eff: " << d.eff                // ERROR HERE
	       << std::endl << std::endl;

The reason is that d.eff is a vector<int> and you don't have an operator<< for the vector.

You might like to write it out with this

copy(d.eff.begin(0,d.eff.end(),std::ostream_iterator<int>(std::cout,","));
std::cout<<std::endl;

but there are other ways.

The output from g++ will tell you the error BUT you have to start with the first line of the error. It often helps to pipe the output into a file and read it with no line wrap eg. [in Linux/Unix bash shell]

g++ test.cpp 2> error.txt
vim error.txt
:set nowrap

the set nowrap command is given in vim but your favourite editor will be equally suitable.

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

Can I add that you have also got a numerator and num, denominator and dem in the class.
That is also an area of confusion.

StuXYZ 731 Practically a Master Poster

There are a few little errors:
(a) You have tried to write a factor that somehow works on the whole array.
(b) You have forgotten that if you get clever and add two factors because any number N, has factors 1 and N. Not to test them
(c) why does factor return a double?

double factor(double data[], int n)   // this should take a number N
{
int facts = 2;
for (int j=0; j<n; j++)        // THIS loop should be j=2;j<N;j++
{
  if (list[j]%2 == 0)   // THIS is wrong 
  facts++;
}
return facts;
}

Please turn on your compiler warnings and never ignore them.

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

There are several problems:

(i) you haven't given us a piece of code that compiles. What is Bp ?

(ii) you haven't given us the input you use , e.g. what does coupon equal?

(iii) Then you use what I think is the differential equation approximation at each step. Have long look at these two lines

rates.push_back(2 * log(100/97.5));
rates.push_back(log(102.5/(100 - 2.5*exp(-(0.5*rates[0])))));

I am no 100% sure on your algorithm but that is not balanced [i.e. in reverse time it doesn't work.

However, if you algorithm is correct (on paper say) then use a numerical error class instead of double. That was actually what I was going to drop in but the failure to compile killed that. - you have host of potential problems with line like:

func=((t - t1)/(t2 - t1))*r2 + ((t2 - t)/(t2 - t1))*r1

as t2 and t1 are very close to zero.

StuXYZ 731 Practically a Master Poster

Sorry dustreader, but if you are going to be using the STL, do this:

// Assign players in any order (not random)
shuffle(players,players+10);

The code given is horrific. It has three vectors etc...

However Calyso8 is starting, so it is important for him/her to understand the algorithm and what the c++ is doing:

Let us look at the required algorithm you want 10 players to have a
fixed number of thing. So just like dealing out cards you start with
10 cards which have 5 innocent, 1 doctor, 3 mafia , 1 cop.

Then you deal the cards to each player.

In code that looks something like this:

// SET CARDS:
int players[10];  // Unassigned at the moment
int cards[10];
for(int i=0;i<5;i++)
   cards[i]=3;
cards[5]=1;  // doctor
cards[6]=2;  // cop
cards[7]=cards[8]=cards[9]=0; // mafia

// DEAL Cards:
int numCards=10;     // Number of cards left
for(int i=0;i<10;i++)   // loop over players  
   {
      
      const int cardNumber=rand() % numCards;
      player[i]=cards[cardNumber];
       // NOW the clever bit : Move the last card to the used slot.
      cards[cardNumber]=cards[numCards-1];
       numCards--;                  // subtract 1 from the number of cards
  }

// Done:

That can be "shortened" and you can optimize out a number of the varables but this is an attempt to allow you to see the algorithm.

StuXYZ 731 Practically a Master Poster

First off: Fix your compiler warnings. They are there for a reason.

e.g. storage[i]="\0"; should be storage[i]='\0'; .

Your memory problem is because in both constructors [that are ambiguous by the way] you allocate storage but do not allocate or even set to zero the memory for each location in storage.

You are going to either:

(a) have to allocate a space for the strings, AND keep a record of how long that is, since the null terminator will tell you when the actual string ends but not the memory space

(b) Write a short string class to do that for you, and make stringArray a storage for for a number of string objects.

I recommend (b). Note that you have not broken the terms of the assignment because you have written your own. i.e. not use the STL.
however, you might like to clarify that point.

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

Actually, it is only partially true. For many template classes you know that you are only going to have a few well known types to create. In that case you can use explicit template initialization. e.g.

//file  test.h
template<typename T>
class test
{
   T x;
public: 
   void addStuff(const T&);
   // ... 
};
// FILE: test.cpp
template<typename T>
void test<T>::addStuff(const T& A)
{
    x+=A;
} 
// THIS IS THE BIT TO create instances
template class test<double>;
template class test<std::complex<double> >;
template class test<int>;

So as you can see you can separate BUT you have to know what you are going to need. It is reasonably easy to do if you are the end user of the templates AND it speeds up compiles dramatically.

I have some (horrible) perl scripts that strips the error file from gcc to add the correct instances, but it isn't that difficult to do by hand or write something a million times better than my scripts.

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

So, the loop that I'm using is incorrect? But the program works perfectly...huhu...

No the program doesn't work ALWAYS:

Enter a=4.4 b=5.5 and then why does this not find the root at
4.493409 ?

Or -4 and 0.5 does not find the root at 0.


That is the problem with the loop, it fails as it skips over the singularities. This can be corrected .

The errors that exist are :
(a) If f(a) >0 and f(b)< 0 then it fails
(b) If f(x) within the range a -> b has a singularity it CAN fail [but not always].


Otherwise the program is kind of ok. It makes too many calls to f(x)
[cache the value and then use it in the fabs test.]

The algorithm is best tried with pen and paper and a graph.
use gnuplot and type plot tan(x)-x and you will see the mess that this function is.

StuXYZ 731 Practically a Master Poster

Why don't you use dynamic_cast. E.g.

class Base {};
class A : public Base {}; 
class B : public Base {};

Base* Aptr=new A();
Base* Bptr=new B();

A* Ax=dynamic_cast<A*>(Aptr);   // sets Ax to a Ax pointer. 
A* Ay=dynamic_cast<A*>(Bptr);   // sets Ay to ZERO
StuXYZ 731 Practically a Master Poster

If you want help.. ask a question, I certainly have not the slightest idea what your problem is , what you are trying to do and what c++ code you have currently written.

Note: When you post code use code tags.

Please read the forum guidelines.

StuXYZ 731 Practically a Master Poster

I know how bisection method works..It just that I don't know how that loop can make it work..

Well the real problem is that the loop does not work. Or more accurately only works for the specific instance when f(a) <0 and f(b) >0 and there is only one root between a and b.

To actually understand what is going on you are going to HAVE to go through it with a piece of paper.
(i) Draw the graph of tan(x)-x
(ii) Observe that it has multiple roots - near [TEX]\pm\pi/2 + n\pi[/TEX].
(iii) Observer the discontinuity at exactly [TEX]\pm\pi/2 + n\pi[/TEX].
(iv) Observe that for +ve x the discontinuity is on the right of the root and for -ve x it is on the left.
(v) Obsever that there is a root at x=0.

So in all tan(x)-x is an awful function to test first, use a polynominal, until you understand the method. [which doesn't have a root at x=0 since that always leads to lots of programming errors.]

Next: take the graph of your function and mark the variables a,b and x, on the x-axis. Just take three different pens/pencils and put them vertically on the correct x-axis point.

Step through the code adjusting the pens as the variables change.

In short bisection is the same as the childrens game, guess a number, were you are told higher and lower, you remember a, and b as the highest …

StuXYZ 731 Practically a Master Poster

Have a look at the boost::any class. http://www.boost.org/doc/libs/1_41_0/doc/html/any.html

If you combine it with some of the typelist ideas in the boost::mpl then you can basically do what you want.

The downside is that this style of programming often looses type safety, which is "a bad thing" as it moves compile errors to run-time exceptions.

StuXYZ 731 Practically a Master Poster

Do note: that for years before 1582, leap years where EVERY 4 years.
There was no 400 or 100 year rule. Prior to 325 the system was
1582 is a mess. Since they did not have a 5-14th October completely (10 days).

It you are in in Britian/America it wasn't 1582 BUT 1752 and the days dropped needed to be 11. (September 2nd was next to the 14th).

So that makes the "correct program" very interesting problem.

StuXYZ 731 Practically a Master Poster

Ok the ugly cin.ignore is simply unnecessary. I have no idea why you might need it, it ignores the next 10 characters of input (say 10 random letters upto a return. Very strange. The std::endl should flush cout, so it should work. If you are using an old compiler you can add
cout.flush().

Other things that you might have wrong are that the call E2.setFirstName(fstname); might actually be to a method like this void setFirstName(std::string&); and then it changes the variable fstname.

I would also like to see some initialization of E2, and addition to the main list of employies. [along with some checking].

hope this helps but without some more code I can't help much more.

StuXYZ 731 Practically a Master Poster

Several problems are apparent.
(a) Turn is not initialized so will definitely be wrong
(b) loop variable j run 0 to 3 inclusive (j<4). so you access undefined memory locations in rot.
(c) rot is local only to the function rotate so the whole function is pointless. [make it global if you want it to work like that]
(d) clrscr; is incorrect, you must have it as clrscr(); if it doesn't take any parameters.
(e) I am sure you have function copy wrong, you use [0][1] rather than [0].

That will do to start.

StuXYZ 731 Practically a Master Poster

The problem you have is that your are using bare pointers. If you were using boost::shared_ptr or even std::auto_ptr then no problem.

So how to delete. You need to do TWO things: (a) delete the memory that the pointer points to, (b) delete the reference.

If you are deleting only one reference then that is easy.

Assuming that you are using vectors:

std::vector<Diary*> V;
std::vector<Diary*>::iterator  Ivec;
//
// Ivec get set / V gets filled etc.
// ...
delete *Ivec;
V.erase(Ivec); 
// NOTE : Ivec NOT not valid:

You can use the return of vector.erase to give you the next valid iterator. You would do that if you are looping through the vector and deciding which to delete . e.g.

std::vector<int> XV;  
  for(int i=0;i<10;i++)
      XV.push_back(i);

  std::vector<int>::iterator xvIter=XV.begin();
  while(xvIter!=XV.end())
    {
      if ((*xvIter%2))
	xvIter=XV.erase(xvIter);
      else
	xvIter++;
    }
  
  copy(XV.begin(),XV.end(),std::ostream_iterator<int>(std::cout," : "));
  std::cout<<std::endl;
}
StuXYZ 731 Practically a Master Poster

The trouble is that advance does not return an iterator, AND the iterator
(i in your code), has to be double derefrenced because the iterator points to a pointer and hence the error message. You need:

advance(i,a);
if ( (*i)->getName()==someVar )
{
}

Note I have added the extra brackets for clarity.

HOWEVER : if you have lots of calls to the advance method you really would be better off with a vector, but you can obviously test the runtime performance.

Carrots commented: Thanks buddy! :) +1
StuXYZ 731 Practically a Master Poster

Just a quick comment (again). The problem I though was not using printf. Yes I know that is not very C++ but if you need exact formated output, you normally end up at the boost::format class. That still needs separation of different type.

So you can write a quick functional separator (or use the boost::mpl) and then EVERY time you call the functional your get the correct version called. In addition, if you make a mistake and use a type that you have not schedules it for you get a compiler error which is EXACTLY what you want. [Since std::cout is often to accepting and boost::format is runtime.]

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

Well I have written a system for extracting maths equations from input text which I currently use in several projects. So I just want to ensure you know what you are getting into it is about 2500 lines of code.

So structure:

you can break the functions down into a tree or a stack. I used a stack system (effectively reverse polish). This leaves a parsing issue.
I used two level parse. (a) the first parse found errors. e.g. bracket errors, syntax errors e.g. 5+-4 is ok but 5+*4 is not, function errors,
sin(56) is ok sinx(56) is not, and so on. Then the actual compiler (into a stack byte code is a lot simpler.

Use a lookup-map for variables. Write a generic functional for a maths component.

Post stuff as you go along, it is going to take you two weeks if you are an experienced programmer. Write lots and lots of test code. Enjoy writing it!

StuXYZ 731 Practically a Master Poster

I am sorry I don't like jonsca's solution, it has ugly temporary variables, that aren't necessary.

The better way to do this (IMHO) is to add two operators. One is operator<< and the other is operator>>

std::istream& operator<<(std::istream& FX,complex& A)
  {  
      A.read(FX);
      return FX;
  }
std::ostream& operator>>(std::ostream& FX,const complex& A)
  {  
      A.write(FX);
      return FX;
  }

Now those two functions allow your to write

complex c;
std::cin>>c;
std::cout<<"You entered "<<c<<std::endl;
}

The only thing you have to write is read/write

void complex::write(std::ostream& FX) const
{
    FX<<r<<"  "<<i;
}  
// AND
void complex::read(std::ostream& FX)
{
   FX>>r>>i;
}

I would add checking etc, to read and allow stuff like 4+i5 etc. I normally don't put the endl within the write function, because it is normal to allow a chained set of functions e.g. std::cout<<"Complex to add are "<<cA<<" + "<<cB<<std::endl;

StuXYZ 731 Practically a Master Poster

Ok, for maths courses have a look at the MIT lecture page http://ocw.mit.edu/OcwWeb/Mathematics/index.htm.

The undergraduate stuff is a great revision guide and most of it I would expect anyone in the field to understand/know. This graduate stuff is a fantastic resource, anyone working with computational geometry will have a good grounding in a lot of this stuff. But there was lots here that I didn't understand as deeply when I went through it.

Note: Maths is not a "understand and know" subject. You should read a maths paper, and try to get an overview, then read it again and get a bit of a deeper understanding and again and again and each time you aim to get slightly more understanding.

However, it is particularly important to do the problems. If you don't do the problems you get a big gap between the stuff you think you know and the stuff you actually know.

Finally, I would like to say something upbeat but maths is hard, I think it is like playing a musical instrument, it requires serious work before you are competent.

StuXYZ 731 Practically a Master Poster

This code is a mess, and 99% is that it is mixed c and c++ , it has not been set out tidily so neither I nor you know what is going on.

Things to fix:

Why use malloc to allocate memory use int* wt=new int[5]; Then remember to delete that memory. You fail to do that in your code because if you get the the return NULL you will have made a memory leak.

The loop construction: for(int i=process[j++];i<=nProcess;i++) is 100% too complex. There are nProcess and process has n variables
so what about for(int i=0;i<nProcess;i++) So if process[0] is > nProcess you stop that is wrong.

Then further stangeness, j goes to 1 and stays there,so why write arrivalTime[j+1] so why no write arrivalTime[2] .

The next problem is that you write

if ((arrivalTime[j+1]+burstTime[j+1]) > 
		(arrivalTime[j+2]+burstTime[j+2]))
	      int temp=process[j+1];    
	    process[j+1]=process[j+2];
	    process[j+2]=temp;

Unfortunately, you declare temp again, and that MASKS the original temp. e.g consider this

int temp=1;
 if (1<2)
     int temp=4;    
    std::cout<<"Temp == "<<temp<<std::end;;

This piece of code prints 1 it does not print 4.

Finally, why pass nProcess when this routine only can deal with 4 entries.

StuXYZ 731 Practically a Master Poster

This forum and others see this question a lot and you get answers that range from none - > everything.

So I will point out something that I have noticed, I have never studied and understood any maths that immediately looked useful, but I always seem to find that it is useful later.

[Note: I often started studing some area of maths because I thought it would be useful, but on actually obtaining some understanding I am normally impressed by its beauty but not its usefulness, that comes later]

Other than that, you are going to need lots and lots of maths for those two fields, lots of calculus , functional theory, vector analysis, fourier and Laue transform analysis, group theory, Baysean theory.
Just scratch the surface.

What you haven't really given us is any real idea of how deep your general maths is? Do you need to go from a good base into specialized areas or do you struggle to take the derivative of a one variable function ? If it is only high-school level (basic caculus etc)
you are really going to have to do the equivalent of about 2 year of a university maths course before you can contribute at the algorithm level. However, lots and lots of code can be improved by good software practice but there is both a status and communication problem level between you and the mathematically able co-works on that kind of project.

StuXYZ 731 Practically a Master Poster

Indeed sfou, it is a method that is absolutely instinctive for most programmers. It is mainly mathematicians that have the big hang up with that sort of construct. They (and theoretical physists) have the most complex if constructs on the planet, they just seem to HATE repeated multiple action if constructs, you always get an if ( conditional) else if (conditional) else from them.

[Quick note: Nothing fundamentally wrong with the way they do if statements, just it is so distinctive ]

Second quick note: Please drop the system("pause") . It really really is evil.

paddowan34 commented: StuXYZ Rocks thanks for the info. +0
StuXYZ 731 Practically a Master Poster

Sorry but the main problem is that you have over complicated the if structure in FindFirst.

Several points

(i) You pass the value first BUT don't actually use it.
Let me elaborate. You use a variable first BUT you don't use the value you pass. So I put the variable IN the function and you just don't have to pass it.

(ii) You also seem to be hung up on putting ONE if / else structure. BUT the trick here (and alot of other places) is to have an if statement and then another if statement. Since I think this idea is very powerful BUT very non-obvious especially people who are still thinking in terms of translating maths I am giving a correct version of FindFirst. It is very important to notice that NONE/ ONE or SEVERAL of the if statements can get executed. This about what happens with an input 1,2,3,4 and also say 2,3,4,1 and 4,3,2,1
All of them return 4.

double 
FindFirst(double test1,double test2,double test3,double test4)
{

   // Finds the lowest value out of test1->4.
 
  double first=test1;
  if (test2<first) first=test2;
  if (test3<first) first=test3;
  if (test4<first) first=test4;
  return first;
}

Finally, have long think about how to understand if statements. The problem you seem to be displaying is you are not breaking them down into their constituent components. So please consider:

if (A>B && C>D)
   std::cout<<"This is true"<<std::endl;

Now that translates to If (A>B) AND (C>D) which implies that
if …

StuXYZ 731 Practically a Master Poster

Ok you have a number of problems:
So let me (a) post some working code: (b) tell you what each line does:

int main() 
{
  std::fstream bfile("file.bin",
           std::ios::in|std::ios::out|std::ios::binary); 
  
  int a = 2;
  int var(0);
	      
  bfile.write(reinterpret_cast<char*>(&a), sizeof(int));
  
  bfile.seekg(0,std::ios::beg);
  bfile.read(reintepret_cast<char*>(&var), sizeof(int));

  std::cout << "Variable:" << var<<std::endl;

}

Note that I have (a) added an int to main.
(b) used reinterpret_cast< > instead of the c cast [good practice -- not essentual.] -- Many people use a union for this.
(c) Added a go to the beginning of the file.
(d) Add a std::endl to the output stream otherwize you might not get any output if you have more code below and it say waits or something.

StuXYZ 731 Practically a Master Poster

Ok the original post was about gcc, which has a tolower function that
does not return a char, it returns an int and takes an int. That is because it works with internationalized character sets. So you do a functional composite to convert the form both ways or just write a quick function like this (you can use a functor if you prefer).

char charLower(const char& P)
{ 
     return static_cast<char>(tolower(P));
}

transform(A.begin(),A.end(),A.begin(),charLower);

Additionally you do also need to remove the pointer redirection (the *) in the erase line gameName.erase(*myIterator); as pointed out by firstPerson. And once that is working you can start debugging.... Enjoy.

StuXYZ 731 Practically a Master Poster

If you do write your own Gauss-Jorden elimination procedure, be very careful to deal with the huge numerical rounding errors. Re- stabalization of matrix after most steps is essential. Also please not
the obvious test matrix [1,2,3][4,5,6][7,8,9] has zero determinate so has no inverse.

Simple approaches in books like numerical recipeshttp://www.nr.com/, e.g. pivoting are a start but much better methods exist (e.g. partial row summation).

Note the NR book is freely viewable.

StuXYZ 731 Practically a Master Poster

As far as I understand the standard, this is not possible .

There are slightly upsetting work-arounds.

First: If you don't need the virtual aspect, this is easy use a template return type. Easy.

Second: If you require the virtual part you can then return A_1 from B_2::foo. [You can get one part to return a A_2/B_2]. And then you have to cast is up later, since you can write virtual A_1* foo() { return new A_2; } BUT I loath the dynamic_cast that is going to be required if A_1 and A_2 are not access only via virtual methods [e.g. A_1 is not an interface class].

However, IF you are accessing an object of B_2 via a virtual function , you have to expect that you will not get a A_2 point back and you will be accessing the points methods via virtual methods and the conversion to A_2 doesn't matter.

Anyway , not really a solution, just some random thoughts. Sorry

StuXYZ 731 Practically a Master Poster

Ok I am not going to deal with all of this mess but point out some of the basic errors and then ask how did you manage to get to this point.

-- Talk your first effort,

double 
Individual:: SchwefelsProblem(vector <double> schwefel_population)
{    
  for (int i=0; i <schwefel_population.size();i++)                 
    square_of_sums=square_of_sums+ schwefel_population[i];
        
  cout <<"The Sum of all elements in the vector is " << square_of_sums <<endl;
     
  for(int j=0 ; j<schwefel_population.size();j++)
    sum_of_squares=sum_of_squares+pow(square_of_sums,2);
  cout <<"The sum of the entire sumation squared is "<<sum_of_squares<<endl;
  return sum_of_squares;
}

Ok errors/mistakes:

(i) No use of const
(ii) No use of references .
Point 1+2 says that you should have written double Individual::Schwefels(const std::vector<double>& PopVec) (iii) General use of using namespace std; -- You are not writing your first c++ program so don't do this.
(iv) No use of iterators -- forgivable since you are learning but maybe think about these two pieces of code:.

sum=accumulate(Pop.begin(),Pop.end(),0.0);
// AND:
double sum=0.0;
std::vector<double>::const_iterator ITvec;
for(ITvec=Pop.begin();ITvec=Pop.end();ITvec++)
   sum+=*ITvec;

(v) You are using square_of_sums without initializing it. Don't tell me you did it in the constructor. This function will be called 100s of times so it will give junk answers.
(vi) You write for(int i=0 ;i<Pop.size();i++) Well that gives you a warning on your compiler.... You didn't either
(a) turn warnings on or (b) fix it.
This is the quickest fix for that warning (assuming iterators don't appeal): for(std::size_t i=0 ;i<Pop.size();i++) (vii) If you want the square of the sum you …

StuXYZ 731 Practically a Master Poster

First thing that comes to mind is that a[9] and c[9] are not initialized.

Next you are using variables columns and row. So check that this->rows == u.columns. Then set the data in this. as c[] is just ignored.

Other than that it looks ok.

StuXYZ 731 Practically a Master Poster

First off, you cannot write fractions fractions :: operator/(fractions f); within the definition of a class.

Second, you have provided a default constructor that set the fraction to 0/1 . That gives perfectly acceptable results. So which test is wrong??

Third: You have not used references in many of your function , so there is lots of unnecessary copying

Forth: The biggest failing the the lack of code reuse. You have addFraction and operator+ using the smae code. PLEASE call one with the other. Otherwize you have two places to change each time and that leads to a mess.