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.

StuXYZ 731 Practically a Master Poster

Well you don't seem to have written a operator>> for class ballTeam. I could be wrong since you didn't include the definition files (.h files).

I

StuXYZ 731 Practically a Master Poster

I am not going to deal with all the things that are wrong here

They include:

(a) a missing = in a test else if (opr1 ='(')
(b) stupid reassignment ifx[i] = ifx[i+1]; but loop on i.
(c) Failure to initialize variables and then do a test of two uninitialized variables
(d) Assuming a terminator char ( ; ) is in a string BUT then default string doesn't have it (i.e. you use ""). So test for the end of the string as well as the terminator.

However, from the code, with templates etc, you are clearly not a beginner BUT the trivial beginner errrors you are making are :
(It does seem that two different programmers wrote myStack and InfixToPostfix. -- these are the infixtopost problems:)

(i) Not using compiler warnings
(ii) writing using namespace std;
(iii) passing everything by value not reference
(iv) Not using the keyword: const
(v) not initializing variables
(vi) not writing copy/assignment methods for complex classes.
(vii) Breaking the program down into subunits, but not testing them individually.
(viii) using varaible names like ifx, which is a minor typo away from a mess.

Number (ii) is the cause of some of your strange error messages since you use a variable called list. This is only possible IF you got the scoping correct....

The whole point of a namespace is to avoid name pollution so don't take it away.

[Rant]
When I interview …

StuXYZ 731 Practically a Master Poster

Seriously, you are just going round in circles. You HAVE TO WRITE SOMETHING SIMPLER so that you get to grips with variables/ if else constructions / functions. And you are going to have to do it in small pieces.

The current errors include, that you have called the function distance, and then used distance as a variable name (without declaration since line 16 is not in scope).

Line 25 distance = squareroot/squareroot; well
that is the same as distance=1.0;

Line 24 would have been written as this squareroot = pow(x2-x1,2.0) + pow (y2-y1,2.0); without the horrible c-style cast. (which is unnecessary).

You are still returning a char* when you say you are returning a float.

You don't have ANY cout<<"Variable == "<<var<<endl; or anything else to actually help figure out the steps that your program is taking.

It will take a complete novice, a couple of hours to build this program up from basics, piece by piece BUT if you insist of trying to do it all in one go, you are going to be here are very very long time. The easiest way to program is alway to make a small modification to a working program that you understand. In your case. start with just the int main() { return 0;} program and add stuff from there.

StuXYZ 731 Practically a Master Poster

This is code absolutely begging for a loop!!

Your actual problem is that you test x then y. That is incorrect. (I think)

Consider a box with coordinates (0,0) and (10,10). I.e it is a square of area 10. Now what happens when you ball is at
(5,23) obviously that misses BUT in your code the first test accept the
point as if only checks the x value and not the x and y simultantiously

You need

if (ballx1 >= boxes[0][0] && ballx1 <= boxes[0][2] &&
    bally1 >= boxes[0][1] && bally1 <= boxes[0][3]) 
{ }

Then just put all 5 box test in a loop please!!

The reason that you should use a loop is that in the copy paste you have made a mistake with boxes[4] and boxes[3].
Note: that line 49 says dirx and I am 99% sure that should say diry.
same with line 39.

StuXYZ 731 Practically a Master Poster

If you have a problem like that and don't understand the compiler error, then split the function into bit, e.g. calculate without the sqrt e.g.

double d=a+b;
distance=sqrt(d);

You have three functions in one line, not a problem BUT it is to you because you can't see what the compiler is telling you. So make it simpler and then you will see what the problem is.

The answer to your question is , yes two things. [maybe three depending on your outlook]

Finally, I ment to add that anyone who does this

float F=function();
if (F==25)
   {
      // This almost never gets executed
  }

is asking for nasty trouble,, the reason is that a floating point number is only equal if EVERY bit is exactly the same e.g. 25.000000000001 is NOT equal to 25.0000000000. So think about how to get round that. Additionally, rounding errors in many functions will lose a little accuracy so although the answer should be exactly 25.0 you get 25.0000001 or something like that.

Additionally, although you may chose to have the sqrt function in your code, you can write it without the sqrt function, by observing that the tests like if (sqrt(d)>10.0) is the same as if (d>100.0) (assuming that d is positive, otherwize nasty things happen with the sqrt).

StuXYZ 731 Practically a Master Poster

The problem you have is temporary values and what happens to them:
I think this will be clear (I hope :)

The problem is that your are taking a copy of the value in the list. This does indeed correctly delete the object. BUT then you do v=0 rather
than *vertexListIterator = 0 ; . Now you access the value in the list, which you have not erased, and then you access the memory area that you have deleted BUT that memory space is marked as deleted but is unlikely to have been over written so you get valid results. If you had done lots of other operations then you might get different results.

Note that if the list was just list<int> and the values were 1,2,3, you would not expect this to change the list:

for(list<int>::iterator ai=L.begin();ai!=L.end();++ai)
{
    int x= *ai;
    x=4;             // This doesn't change anything in list
}

The normal process that would be not to use the temporary.

delete *vertexListIterator;
*vertexListIterator=0

Also please please don't use the C style casts, use a static_cast. That would remove any problems that might arise in-case the list turned out to be of a polymorphic class, and Vertex wasn't the base.

You use reinterpret_cast<long int> in the output of the pointer value to be printed.

schnell commented: Good Explaination +0
StuXYZ 731 Practically a Master Poster

The first problem is that your are returning a string from a function that says it will return a floating point number..
e.g. points has returns "miss" But requires it to return a floating point number.

The next thing is that you have added a comma after each 25 in the function points and a semi colon

e.g. else if (distance == 25,); BOTH are wrong:
This line needs to be else if (distance==25.0) Then correct the other three places you have made those two errors.

-----

You HAVE to go back, start again and write MUCH simpler stuff before you try this. It will pay you back because the next assignment will be much much harder unless you grasp the basics, after that you will easily do all the other assingments.

So write
(a) simple program that inputs a number and prints it out.
(b) then a simple program that takes two numbers and adds them together.
(c) a program that uses a function to add those two numbers together.

At every step ALWAY put print out what you are doing, for example
in the program above you should have a cout<<"ENTERING points"<<endl; as the first line of points, and if need be a cout<<"Line 4"<<endl; after each line, and then print the variables etc. I know it sounds trivial and a lot of work but only when you really understand what you are doing at a …

StuXYZ 731 Practically a Master Poster

If you are debugging code (and that is what you are doing here), you need to step through the code and check your assumptions. That can be done with a traditional debugger that lets you see each line as it is run, or by putting some output statements in the code.

Your errors include
(a) the loop for the factorial never is run. since neither N nor i are changed in the while loop. This should be fairly obvious since you never reached the "factoraila == " statement

(b) you are using a loop to calculate [tex]\sum n^2[\tex] ?? There are simple formula to get the result, no loop.

StuXYZ 731 Practically a Master Poster

First things first: Dont use system("Pause") it has been discussed to death here and everywhere on the web.

Second: The next problem is that you are using temp1 without initializing it. i.e every time you run the program it could start with a different value and you don't know what it is.

Third: you use a struct student, BUT by not having a constructor in this object all the variables DO NOT GET INITIALIZED. Therefore your have another problem.

Four: You really really need an array of students. it would make the code MUCH shorter.

Five : Semi colon after the while (ans=='y' || ans=='Y') ;
is wrong. because then the while does nothing, or loops indefinitely

Six: the reason that your class_ave does not work is that your pass three uninitialized variables. Then you have the logic wrong. Ok. Consider that you wish to pass up to three students, then temp_1 etc
should be the three values the students get.
You might chose to do that like this

// THIS IS IN YOUR MAIN:
class_ave(record1.total,record2.total,record2.total);

Note, the thing that is getting you mixed up is that the values or VARIABLES that you use to call the function are not the same names as are in the declaration of the function, you can equally call the function like this
class_ave(40,45,34);

Note that you have then made another error. Your values in are int. This is not correct, since you are taking an average percentage on …

StuXYZ 731 Practically a Master Poster

Calling the destructor normally implies that the memory is listed as free, i.e. you can quickly find that the memory is corrupted with something else.

Try valgind to get a detailed picture of deleted and valid memory , as well as gdb/ddd to look at the disassembly.

StuXYZ 731 Practically a Master Poster

Let use be a little careful here about the sequence of events.
First off, if you examine the assembler/machine code that is 100% exactly what is going on. However, (a) that may mean that your compiler is being "smart" (b) the standard says what the effect should be. So now we will discuss what actually should happen:

So consider your example. First if the code is written as you have written it.
(a) The object is created
(b) then the code in { } below the constructor is called
(c) the delete operator is called
(d) the program exits.

Now let us write a better example:

class Example
{  
    private: 
        int x;
        double d;
        MyObj MA;
        MyObj MB;
   public:
       Example() : x(5),MA(4,5)
         {
            MB=MA;
         }
};
int main()
 {  Example A; }

Now what happens (assuming MyObj is definded elsewhere).

(a) x is initialized with the value 5.

(b) MA is constructed (calling the constructor with two values 4 and 5.

(c) MB is constructed (calling the constructor with no value e.g MB() (d) Then the assignment operator (=) is called on the previously constructed MB e.g. MB.operator=(MA); (e) the destructor for MB is called

(f) the destructor for MA is called

(g) memory for object A is marked free

e,f,g are the effect of the default destructor begin called.

Does that help / make it clear ??

It is maybe worth playing with …

StuXYZ 731 Practically a Master Poster

firstPerson's answer works and solves the problem BUT for a large classes you might prefer to use explicit instantiation. [which gives the beginner a better idea of what is happening (sometimes)].

so you add a template class HashTable<std::string>; at the end of HashTable.cpp and then you have told the compiler that you require a particular HashTable type.

Then you don't have to change the includes in anyway, and you don't have a huge .h file to include each time.

StuXYZ 731 Practically a Master Poster

What about adding a class. Starting with that is a great way to group data together.

class UserInfo
{
   private:
    std::string Name;
    std::string Pass;      // THIS IS NOT SECURE
    int age;
    // etc...                 
};

But you may want to just use a token index e.g.

class UserDetails
{
   std::string Name;
   int index; 
}

and then use the index number (e.g. your i as a way of looking up a data-entry elsewhere.

This way you can either do something like this:

UserDetails* UPtr= findUser(Name);
if (UPtr)
  UPtr->printUser();
// or:
DataBaseObj DB;
// stuff...
if (UPtr)
   DB->printUser(UPtr->getIndex());

Note: You could sort your list of users and then when you have lots you don't need to loop through all of them.

Also: your current code prints a lot of "your pass was not regonised"
That needs to be after the loop if you don't find a user. So have another look at your if/else construction.

Think about using std::map<std::string,userClass> or std::vector<userClass> or something else other than a simple array. Since you will want to add new users later.

Don't use using namespace std; it simple defeats the objective of namespace std: to NOT pollute your global namespace.

StuXYZ 731 Practically a Master Poster

The reason (for good/bad) is that when the compiler hits instances.inc.
It has not seen the definition of graph.
If you put include instances at the end of graph.cpp all is fine.

Note that you only need the template instance for the class e.g. template class Graph<int,int,int>; since all the methods for the class are build. This should have been flaged as an error by VC++.
[in the same way that if you provide an explicit template function you should not explicitly instantiate it. ]

StuXYZ 731 Practically a Master Poster

It doesn't have an inbuilt function (but I am sure they are in libraries)
BUT surely it is this

int totalMin=890;
int min=total % 60 ;
int hour = (total / 60) % 24;
// etc

not exactly difficult to put into a function.
(A fraction of care is needed if using double values but the same principle.)

StuXYZ 731 Practically a Master Poster

You seem to have two cin>>x in your code at lines 23 and 21. I would delete line 23.

I might make count and integer but that is minor.
you have remembered to initialize your variables which is good.

StuXYZ 731 Practically a Master Poster

Yes the problem is name reuse. The code compiles fine if you cahgne the name OR you put allocator in a namespace e.g

namespace X
{
template<class T>
class Allocator{
  
public:
  Allocator(void){}
  
};

}

template<class NodeData,class Real=float>
class OctNode
{
private:

public:
  static  X::Allocator<OctNode<NodeData,Real> > Allocator;
};
StuXYZ 731 Practically a Master Poster

Well this looks like a c program (not a c++) so I will assume that you are in C and carry on.

The first question is that you have unfortunely added a \n after the %d in the scanf statement. That means if first looks for a number and then and extra return. So remove the \n and things will be ok.

Next problem is that you don't ask for a choice. You print the question but have forgotten to actually get user input (e.g. with a scanf)
then choice is zero and things go wrong.

Ntex you have written else if (choice != 1,2) this is not the correct way to write this you since it . This statement means find the result of choice != 1 then find the result of 2 and if that answer is true execute the statement below Well 2 is always true so it works. Much simpler was to write else .
[NOTE::
you could write else if (choice!=1 || choice!=2) .

finally : You don't want the break at the end.

Best of luck with it. What did you program 17 years ago, basic or assembler I guess. If it is the latter you will pick this up really quickly.
(Maybe fortran? -- again this wont be problem after pointers).

StuXYZ 731 Practically a Master Poster

Well ok then don't word the problem as if it is verbatim from the question sheet. Doesn't matter were you are tell us what you have got.

The problem can be broken down in to several parts (a) start
(b) read in the input (or a bit of it) (c) process that input. (d) give output.

I put (a) up there because that is were you will want to initialize state and things like that.

Now were are you ??? What have you managed? What specifically have you failed to do ? The basic rules here are post something, pseudo code if you wish, C++ that doesn't work, just about anything.

-- Programming has a lot of unspecifics, if there is no file name then it is a runtime variable. Ie, the user gets to choose, but if it makes it simpler you choose a fixed value e.g "script.txt" Then generalize you program later.

-- When you read the post forum rules it said don't do peoples homework for them but help them understand what they are stuck on.

StuXYZ 731 Practically a Master Poster

That doesn't sound useful idea. Consider this

(a) A polynomainal multiplication is a N * M process were the length of the polynominial are M and N.
(b) The polynominal can be sparse e.g. x^8+x.

Ok: the first thing is that an linked list can be used for almost ANY computer data/algorithm, for example Knuth shows the proof that a tree structure algorithm can be converted into a linked list algorithm
(at a cost of efficiency).

Second were do you want to go with this. If you have a REALLY sparse polynominial and you want to move to some kind of list, but a vector (for random access is better), which holds the powers and coefficients.
BUT the key element against a linked list is the insert construction is not likely to happen (or can be easily avoided). e.g consider multiplicaton. This can be done (low to high) or (high to low) . Let us consider high to low. Consider two polynomials with powers
A1,A2,A3... and B1,B2,B3.. where A1>A2 etc and B1>B2 etc.
Now the first multiplication you do is A1*B1 which gives the largest power, then you consider A2*B1 and A1*B2 either one must be the bigger term and hold the result of the other, then continue down the lists. You then have constructed in order the polynomial produce with the use of only one tempory and is it also ordered.


Now what else would you like to …

StuXYZ 731 Practically a Master Poster

Welcome to the real world. There is not free lunch.... sorry.
So
(a) either attend your classes and actually pay attention.
(b) decide that the class is not a good use of time and instead study some books in the library.
(c) Fail your degree/course.

But because this is the real world, I care very very little other than if you pick option (c), you just might be competing with me for a job, and then I will have a little smile on my face.

To go from zero knowledge to that assignment is about 10 hours of reading. (I would figure it is 6 lectures (50min) and corresponding work
(5 hours)). That is one long evening.

[Quick note: option (b) was taken by a a REALLY bright individual at my college and he did really well -- although his invidual exam marks had a huge distribution]

StuXYZ 731 Practically a Master Poster

You could use some of the object orientation stuff , i.e. if all the variables in an object are private, then you can add a flag that they have been changed, when they are accessed via the setters/public methods.

Alternative, use a checksum. I would keep two numbers (a) the total memory and (b) MD5 sum. That would give >99.99% accuracy.

If you need 100% certain then create a copy (using the copy constructor and assingment operator) and compare. Depending on the class, you are going to have to be careful about what constitutes a difference e.g. comparing to doubles without a tolerance is normally going to not give equallity even if they are actually equal due to rounding errors. You can get hurt by the late on things like compiler sequences e.g (a+b)+c can differ from a+(b+c) .

So in short, a little context is needed or a reasonable amount of thought about what you are trying to achieve. An old programming saying I have heard is Programming is maintaining two goals, the exact logic of the silicon and the illusion the user requires .
[sorry if I have quoted that incorrectly but the sense is valid]

StuXYZ 731 Practically a Master Poster

Tough. Try telling that to the standard committee. Section 13.10 tells us that when an template is explicitly instantiated it is necessary to create ALL the methods. Additionally the compiler is no required to resolve multiple instansiation hence it is wrong to put it in the .h

Windows has the whole project in VS, so it can play with the standard but if you try to link various dll's I suspect that it wouldn't work.
gcc works of a file by file system so you can't.

StuXYZ 731 Practically a Master Poster

Sorry my fault about not being clear about point 1.

your code is

template <class E>
nodePtr<E> BinaryTree<E>::getNode(E item){
nodePtr<E> temp = new nodePtr;
temp->data = item;
return nodePtr;
}

Note that you call E's copy constructor for item and then you call E's assignment operator to set temp->data. That is not something the optimizer can remove. Since both the copy and assignment operators can have side-effects.
Try this

template <class E>
node<E>* 
BinaryTree<E>::getNode(const E& item)
{
node<E>* temp = new node<E>;
temp->data=item;
return temp;            
}

That corrects a multitude of errors:
(a) you can't return a type. (nodeptr)
(b) you can't use a templated templated pointer
(c) you cant have open template typedef. [explicit is ok]
(d) you avoid the double copy.

I have not added a node<E>(const E&) constructor which I think should be done. And you MUST add a constructor to this struct since you will have pointers that point to a random location if you don't

Anyway hope that helps you get further

StuXYZ 731 Practically a Master Poster

Basically your template instantiation is in the wrong piece of code.
It should be in the Temp.cpp.

Why: To create an instance of a class you have to have all the methods available to the compiler. You can be doing absolutly anything with typename T. So it has to be in the cpp file. [You can have it in the .h file BUT you have to be VERY careful it is instantiated only once]

StuXYZ 731 Practically a Master Poster

It is that your decrement of y does absolutely nothing.

total start as???? Absolutely anything.

Your function is not recursive, it doesn't call itself. Imagen you call your function like this myMath(3,4); Let us step through and see what happens:
ok

// This is the effect it is NOT code:
x=3; y=4                :     line ::        int myMath(int x, int y) 
total = ANYTHING         : line :: int total; 
Take branch           : line :: if ( y > 0) {
total=ANYTHING+x       : line ::total = total + x;
y=3;                       : line :: y--
// Compiler error here: reached a function and have not return.

y is LOCAL to the function only. if you call it again with myMath(10,7)
then y will be 7.

To be recursive you need to call myMath FROM inside myMath.

StuXYZ 731 Practically a Master Poster

Your problem is the subtraction of y. It doesn't do anything.

The point about recussion is that in a default case you
return a value e.g. if (y==1) return x; but in more general cases you return a simpler function .e.g if (y>1) return add(x,y-1); However, once you get that to work for postive x and y, note that with a very small change it will also work with negative x and y.
(and show and interesting demonstration as to why -3 * -4 =12. )

[tinfoil hat]It is not a proper mathematical proof[/tinfoilhat]

StuXYZ 731 Practically a Master Poster

k will use code tags, np and i know that it pointless to use templates when you are trying to pass values by value in your class. however, I did not design the calss.

(1) It is not pointless to use templates just that it is better to use references.
(2) However, designed the class didn't design it well enough to compile so it that is sufficient excuse then sorry...
(3) Have you actually read the orginal posts and fixed the compile errors?

StuXYZ 731 Practically a Master Poster

Ok first USE CODE TAGS. Sorry to shout but it is written in the introduction to the forum, it is written as the top announcement to this and almost every forum. e.g http://www.daniweb.com/forums/announcement8-3.html.

Second: Do not expect help after a "bump" post. I tend to get back to posts I have contributed to but normally once a day.

Third when adding extra posts to a question show a slight indication that you have (a) read the previous posts (b) read the error messages that your compiler has written out. (c) notice we are using code tags.

So let me see errors starts on line 27.

template <class E>
nodePtr<E> BinaryTree<E>::getNode(E item)

Surprised, Now read my first post. Then fix.

While you are at it DONT pass template class objects as value, but as reference. Image E was not int but say a 500kb class. In this case use const E& Sorry for the harsh reply, but help is normally gladly given, but in return I expect to feel that I make a small difference, in this case the that hasn't happened.

StuXYZ 731 Practically a Master Poster

Just a quick note, since you look like you are going to get confused.
You really need to be working with double or floats, e.g.
3.4 or 34003.384 or 1.87561e2. Even if you input standard integers
sqrt(2) is not an integer.

You are also going to have to test for numbers below zero. Are you going to accept sqrt(-1) (which is the complex number (0,i))

StuXYZ 731 Practically a Master Poster

I think you need either: while(Choice!='n' && Choice!='N') { } Note the && (and).

OR: while(tolower(Choice)!='n') { } Also please note you are very unlikely to need the ; after the while
unless it is in a do { } while (condition); construction.
Whatever you want executed goes in the brackets.

StuXYZ 731 Practically a Master Poster

First off, shurik_r got most of that correct, however, you cannot use
typedef for unspecified templates , so you cant write

// THIS IS NOT ALLOWED 
template <class E>
typedef node<E>* nodePtr<E>;

However, you can do this should you wish

typedef node<int> nodeInt;

The correct way to write a template forward declaration is this

template<typename E> struct node;

Actually, you don't need the forward declaration since you have a full declaration of node. And nodePtr is a horrific mess when node<E>* seems easier to read (to me).

StuXYZ 731 Practically a Master Poster

The normal way to do this is to use a stringstream.
Now you have to be VERY VERY careful, with this.
The reason is that if you do

double Res;
std::string A="3.4e5x"
std::stringstream IX(A);
A>>Res;

This cose will happily set Res equal to 34000. Which is not correct.
So Try this:

// This function returns true if the number is valid
// and sets Res to the correct number
template<typename T>
bool 
convert(const std::string& A,T& Res)
{
 std::istringstream iss(A);
 iss>>Res;
 return (iss.fail() || iss.tellg()!=A.length()) ?
   false : true;
}
StuXYZ 731 Practically a Master Poster

You can compile everything as separate files BUT to get an executable you need to link all the files required.
e.g. in three command do this:

g++ -Wall -c Taddmain.cpp
g++ -Wall -c Tadd.cpp
g++ -Wall -o Taddprog Tadd.o Taddmain.o

or in one coamnd

g++ -Wall -o Taddprog Taddmain.cpp Tadd.cpp

There are other ways, including making a library. If you are interested you can read about it in the gcc manual or post further questions here.

However, very well done for using -Wall (warnings all) you will benefit greatly from this, and I have added to your reputation for that because I guess about 1/3 of the questions here would be self-solved if other did that.

StuXYZ 731 Practically a Master Poster

Ok there are many many thinks to really really dislike about this code.
In particular is the "cleverness".

Ok first, it is int main() . That has been said a million times on this forum.

Second for (sigma=ii=0;ii<n;ii++) thsi is C++ so (a) reuse index i and declare it in your loop like you have done for the first loop in your code. Second the "clever" sigma=ii=0 is a mess since (i) sigma is a double and ii is an integer and you would have been lots better to write double sigma(0.0),sigma2(0.0) ... etc. on the line above.

Then you make a mistake -- your see scores points the first point in the memory you allocated and you proceed to change that by using it as a point -- so by the end of the first loop (to get mean) you have scores=original_scores + 5 * sizeof(int).

The you don't reset it --- oh --- that means that the next loop is junk, since score loops over the NEXT 5 values that can be absolutely anything.

Finally you allocate memory so please remember

For every new there must be a delete.

You are well able to fix your code by (a) using array indexs e.g. scores or (b) by using a new pointer that is not allocated e.g

double* sPtr=scores;
for(int i=0;i<n;i++)
    sum+=*sPtr++;

Finally: Do you know that the line strDev=pow(sigma2/n,1/2); is the same as either strDev=pow(sigma2/n,0); strDev=1.0; Think about …

StuXYZ 731 Practically a Master Poster

The problem is that you have a map of type
map<string,list<pointer> >.

You are doing two thing wrong:

std::map<std::string,std::list<Operation *> >::iterator labelPtr;
labelPtr = this->labelOPMap.find(currentLabel);
// NO CHECK FOR not found e.g. labelPtr==labelOPMap.end()
// currentLst does not point to anything: it is not initialized
*currentLst = labelPtr->second; ]

These two problem guarantee that it will fail.

StuXYZ 731 Practically a Master Poster

well then the first thing to do is to find out if you get to your first system command. Put a std::cout<<"TEST"<<std::endl; exit(1) at line 17 of your main. Then see if you get that without a seg fault.

If you don't then you have an error in the constructor of System.
If not then it maybe the system command and so on. A debugger can help here lots.

StuXYZ 731 Practically a Master Poster

Actually, if you are doing a binary search, make 100% certain that you understand the algorithm in 1D. That is important since 2D array can be easily thougth of as a 1D array. The binary search can be done recursively
but let us start with the simple 1d binary search.

It REALLY helps to do this on paper with three coloured counters that you place on the number the index points to.

consider a set of numbers that are ordered, for simpicity consider
0-99. in linear order.

Now set target = 43  (anynumber between 0-99 will do)
        set first =0 
        set last = 99
        set mid = (first+last)/2 = 49 (remember integer arithmatic)
        
// Loop over
            while(mid!=target)
               {
                  if (mid>target)      // obviously last>mid and it is also LOTs 
                     last=mid;          // bigger than target
                  else  
                      first=mid;
                  mid=(first+last)/2
              }

Understand how THIS works.

Now continue to see that if you have an ordered array of 100 points.
Then first,mid,last represent the array index and the values in the array are only used in the test to see if array[mid]>target.

This is only a fraction away from a 2D array, and slight modifications away from a recursive function.

StuXYZ 731 Practically a Master Poster

Note 100% certain I follow what you are trying to do.
But some points:

(a) C++ is almost space insensitive. The only areas you have to worry are in the middle of keywords e.g. cla ss A { } is not acceptable, nor in the middle of stuff like operator<< e.g. std::cout< <"Hello"<<std::endl; (b) Consider your code:

if(first <= last)
{
int mid = (first + last) / 2;
}

This creates a variable mid. BUT mid has scope ONLY within the braces
e.g. only for ONE line of code. Therefore this if and the creation of mid is useless.

Then you try to use a mid LATER but that does't exist so you get errors.

(c) you pass values into your function e.g. first and last, but immediately you assign them to some value from your matrix. This negates the purpose of calling them into the function.

if(key == Values[][mid])

This line does not work since you have to define the first array index.

Please start with something a lot simpler, try just printing the array, then swapping it around. Doing stuff in stages is often quicker than doing the problem in hand.

StuXYZ 731 Practically a Master Poster

I can't get the code to seg fault but I am running it on linux.

However you have many instances of code like: if (wrote=false) and similar Note: you only have ONE =. This is certainly wrong. Consider the line above. It would set wrote to false and then never execute the code in the error block. PLEASE (a) get a compiler that gives warning messages, (b) FIX THEM. -- I almost missed the == error in the storm of other warning messages.

If you are still getting seg-faults can you suggest the input information you typed to get that error??

You know the basics, don't use using namespace std; , don't name stuff like System etc, that is so easy to miss-type, don't mix '\n' and std::endl; [use the latter], don't pass things by value that would be better by const reference. e.g webaddr to System::Write( ). You will have less problems if you code to these standards, it then becomes instinctive.

StuXYZ 731 Practically a Master Poster

It depends : you have two options:

(a) leave the set unchanged. Simple do return *this; .
You will have to have an suitable copy constructor in you class but it is likely that you have one set(const set&) (b) ok, big error, then throw RangeError; or some such exception. [Note you have two write a RangeError class or use a STL exception class] But be careful to ensure you catch it latter.

However, you cant return -1. That is not acceptable (unless you can cast -1 to a set??? -- you might have added a suitable operator -- doesn't seem like a good idea but .... )

StuXYZ 731 Practically a Master Poster

Well it is definately wrong.

The reason is that the method say it will return an object of set, but -1, EXIT_SUCCESS etc is an integer so it will not compile.

The return from a function is based on what will happen later and how bad it is.

For example consider say [icode]set divide(const set& other)[/icode]
in the above. [multiply is a bad choise since 0 * a number is ok.
What options do we have, well we could have

this->num=5 other.num=2 

that would be a slight problem, since 5/2 in the set of integers is 2. Maybe you need a warning? Or we could hvae other.num=0 and things have gone very wrong.

There are four main options:

(a) set an other variable : status and put the status of the result but always return a valid output.
(b) set the output (if it is a class) to some-predefined error status.
(c) throw an exception
(d) exit the code.

First off, (d) well if the whole thing has gone wrong nobody will want to be running the code, but it can be a bit drastic.
(c) This is a bit drastic still, because if there is no catch block then it is the same as (d), however it allows large objects to be propergated back, and clears up the memory properly in most cases [don't use in a constructor unless VERY careful, never use in a destructor.]
(b) Often acceptable, but …

StuXYZ 731 Practically a Master Poster

As I understand the question: Is there an advantage of using size as a template variable rather than as a parameter in the constructor.

There are probabily several reasons to prefer either approach. But consider what you CAN'T do with a template parameter relative to a constructor parameter.

First:
consider that operator= has been declared for each class, then

genClass<int,50> A;
genClass<int,80> B;

// this is a compile time error [ unless explicityly allowed]
A=B;

but this is at best a runtime error (if you have checking) and not if you don't. Or maybe you allow it/want to accept this.

genClass<int> A(50);
genClass<int> B(80);
A=B;       // No compiler error

If the intension is the first code version, then you have added better compiler error detection. Which is good, since a compiler error is almost always easier and better to get than a runtime error.

Other reasons include that compile time speed. FFT's can be sped up if the size is know at compile time.

StuXYZ 731 Practically a Master Poster

The "best" algorithm depends on the nature of the input and the evaluation metric for "best". Is it only one x that will be compared etc.

It sounds like you have words at compile time. If that is the case, then use template meta-programming and create an alphabetical list of alphabetical entries to search against. Use the boost::mpl http://www.boost.org/doc/libs/1_40_0/libs/mpl/doc/index.html to do that and then use runtime polymorphism to find your target set. That would be very very fast (CPU) time.

Sorry for the useless reply but you haven't shown much effort with your question. What have your thought of and why do you like and more importantly why don't you like what you have prototyped/coded?

StuXYZ 731 Practically a Master Poster

Initially, the first problem is that you are forgetting/didn't know that
if you declare an array of size 5 e.g. char name[5]; then that gives you memory locations name[0] to name[4]. But does not give you name[5] that can be used by the program for something else.

I have just reposted you code, without fixing it but adding a few comments about what is going wrong.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//
// A short program to print the string "Hello, Fred"
//

int main (int argc, const char *argv[])
{
  char name[5];
  char ch;
  char *src = "Fred";
  char *dst;
  dst = name;
  
  // copy the name
  while (*src)
  {	
    src != 0;    // Doesn't do anything
    ++src;       // Increment source before coping first name 
    *dst = *src; // set first character of dst to be 'r' then 'e' etc.
  }
  // dst is now 0. thus nothing in its string.

  
  char *msg = (char *) malloc (5);
  strcpy (msg, "Hello, ");  // memory leak since msg is only 5 long and 
                            // " hello, " is 7 (including 0 on end). 
  strcat (msg, name);       // More memory probelms / leak
                            // This puts msg into NAME.
  puts(msg);
  
  //free (last_char);
  free (msg);                
  
  //free (msg);
  msg = (char *) malloc (5);
  msg = src;                // This losses the memory allocated in line above.
  
  puts (msg);
  return 0;
}

hope it helps