StuXYZ 731 Practically a Master Poster

I think siddhants3 although gave a good answer, mis-understood the question by I_Empire. You can do this:

#include <iostream>

using namespace std;
template<typename C>
class A
{
public:
	A() { }
	template<typename T>
	void Print(const T&);
};

template<typename C>
template<typename T>
void A<C>::Print(const T& item) 
{
   std::cout<<item<<std::endl;
}

int main()
{  
	A<int> t;
	t.Print(3.1415f); //implicitly call t.Print<float>(const float&);
	t.Print<unsigned int>(100); //explicitly

	return 0;
}

Note the use of two templates, the first is the class and the second is the function. There are explicit rules about specialization, which if you are after I recommend posting another question / reading about them in the standard / or experimenting. But I have given the general case.

Now, you have to be a little careful. As I have written it all in one file, there is no problem BUT if you separate the files, then you are going to have to have either explicit or implicit template instatiation. That means if you have a file, say Aclass.cpp and Aclass.h, which have the code and the defiintion of the class, and you use in in another file say main.cpp. There is no way for the compiler to know that it needs a print<unsigned int> for example. If the code is in the actual definition (e.g. Aclass.h) then there is not problem.

So to get round that is automatically is (a) compiler specific, (b) dramatically increases compile time. So you can just ignore the problem and with a couple of flags to …

StuXYZ 731 Practically a Master Poster

well your compile should give a line number.....
What you are not saying is if the error is at run-time or at compile time.

Compile time:

you may have written something like this

const int X(40);       // set X to 40
X--;                          // set X to 39 not allowed.

Run time, you may have written:

int *Ptr(10);   // intending *Ptr to point to a location 10  but 
                      // actually pointing it to location 
// error here:
(*Ptr)--;         // Maybe you intended to write *Ptr--

Actually the last error is a little difficult to find, without using the debugger or a lot of print statements.

StuXYZ 731 Practically a Master Poster

First off please read the formum posting rules about using code tags.
e.g. http://www.daniweb.com/forums/thread78223.html

Second. this program is screaming for a overloaded operator* so you can write Fraction f3=f1*f2; .
The major point about classes is so that you can use them as abstract items.

Small points:
Add std::endl on each of your cout outputs.

The checkGuess is both wrong algorithmically and syntatically.

You need something like this:

void checkGuess(const Fraction& G)
{
    if (G.num==this.num &&
        G.denom=this.denom)
        std::cout<<"success"<<std::endl;
}

But you need to reduce the guess, have an operator>> and operator<<
to allow you to do this

Fraction X(3,4)
std::cout<<X<<std::end;

Avoid using the ? : operator since you are just getting confused. Try an if(condition) { } else { } first, then later you can add them when it is working.

StuXYZ 731 Practically a Master Poster

Good, you are making progress then.

Quick comment: point 4.

A singularly linked list is set up the same way as a double linked list EXCEPT that my step 7 is skipped.

Comment on 1: Consider this:

// single allocation
double* Ptr=new double;
delete Ptr;
// multiple allocations:
int* IPtr=new int[10];
delete [] IPtr;

Use the new/delete in pairs. AND be VERY careful that if you have a set of if/else were you have multiple return points, you delete the memory regardless of the path out of the function.

Later you will start using things like boost::shared_ptr and the problem will go away. [to be replaced with much less-frequent but more difficult to find deletion before lifetime over problems] but this is a lot of code in the future.

StuXYZ 731 Practically a Master Poster

Sorry came a bit late to this thread.

The problem is that you are not using initilizers. Try this:
It disposes of the need to have a default constructor class1(). The important thing to remember is that the code in the { } after the constructor is run AFTER the initializers are run. So you should prefer setting things immediately rather than in that code block.

I have changed some of your variable names since I think you have confused yourself with the nearly identical names.

I have added standard references, it changes nothing in the sence of the code, but means that intermediate copies are not made. (which is normally bad).

#include <iostream>
#include <string>

////////////////////////////////////
class CLASS1
{
private:

  std::string name;

public:

  CLASS1(const std::string&);
  CLASS1(const CLASS1&);              // Always provide a copy constructor
  const std::string& getName() const { return name; }
};


CLASS1::CLASS1(const std::string& xname) :
  name(xname)
{}

CLASS1::CLASS1(const CLASS1& A) :
  name(A.name)
{}


///////////////////////////////////////
class CLASS2
{
private:

  CLASS1 c1object;

public:

  CLASS2();  
  CLASS2(const CLASS1&);
  // added a return reference + const

  const CLASS1& getC1() const { return c1object; } 
};

// this sets with the null name
CLASS2::CLASS2() :
  c1object("nullname")
{}

CLASS2::CLASS2(const CLASS1& xclass1) :
  c1object(xclass1)
{}


/////////////////////////////////

int main()
{
  CLASS1 c1Item("Sean");

  CLASS2 c2Item(c1Item);

  std::cout << "C2 == "<<c2Item.getC1().getName()<<std::endl;

  return 0; 
}
StuXYZ 731 Practically a Master Poster

First: Memory that is allocated must be deleted. If you allocate memory
like f/temp/temp2 and then hit a return you have 100% guaranteed to have a memory leak.

Second: you need to post your declaration of flightnode and other
classes your are using.

Third: Your "end else if" comments just clutter stuff up. The code tells you this. you dump that BUT keep the informational comments. e.g.
"add somehere in the middle".

Fourth you would be better off reallizing that you could do this with less if/else and have two pointer, that bracket the entry position. Then set if not null but use regardless to set.

Linked list A-B-C-D
New node=N
Insert between C and D. 
T1=C 
T2=D
if (T1) T1->setNext(N)
if (T2) T2->setPrev(N)
StuXYZ 731 Practically a Master Poster

You have two options.
The obvious on is to add a counter to the class. This can be done several ways and then each method and submethod adds to the count.

The other (less common and normally less elegant) is to have each method return the number of operations it took. But in this case since you will have private methods etc. I think it will be easier to do option one.

You can even get a bit of object-orientated about it. You can have a derived class that is dij_with_counting, and use a virtual addOperation() , that is a no-op in the base class but does the counting in the derived class. But it is unlikely to be required or worth the effort, unless the code is going into a ibrary.
method that is a

StuXYZ 731 Practically a Master Poster

Can you post your new non-compiling/non-running code please.

The only thing that I can think you might have done wrong is to forget to at const to both the declaration and the instance eg.

class A
{
    std::string print() const ; 
};

std::string
A::print() const
{
   std::string output;
    std::list<int>::const_iterator iterI;
  //...
   return output;
}
StuXYZ 731 Practically a Master Poster

First off I would prefer if you just post your code and not a code snippit as well.

Second-- I would like an atempt at the two functions. So instead of helping you directly with them, I am going to comment on your other functions..
Let me start with :

largestScore
Ok err.. it doesn't print anything:
Second the variable largets is not actually set externally.
E.g. try this in main

int main()
{
   int scores[]={5,6,7,8};
   double large(3.0);
   largestScore(scores,4,large);
   // SURPRISE: this prints 3.0
   std::cout<<"Large == "<<large<<std::endl; 
}

You worry me that you haven't tested anything you have written.
you additionaly convert between integer and double. Your also would have real problems with this input: int score[]={-3,-4}; Initialize your largest/smallest values with the FIRST value, not with zero or some other arbitory number.

Finally: You have made this mistake:

int A(5);
int B(7);
std::cout<<"A/B == "<<A/B<<std::endl;
// this prints ZERO.

Because this is integer division.

PLEASE test your code. ALWAYS regardless of what you think it does.

StuXYZ 731 Practically a Master Poster

You have forgotten to use the return value of flip(). If you did this if (flip()==1) . I think you would be a lot better than looking at your loop count varible.

If really helps lots to run you code on paper, with a list of variables when the code is small and you are beginning. They you would see why you only get one head.

It also helps to printout the results every turn.

tux4life commented: Good suggestion on the code runout on paper :) +23
StuXYZ 731 Practically a Master Poster

This is simple (I hope). You are using an iterator. The iterator allows the method to change the data.

Now since an iterator is a class and your compiler cannot know until link time that the iterator does not change the data, you compiler HAS to assume that the iterator does, hence it doesn't allow const to be added to print.


A simple way to get round this is to use const_iteraror.

Another way is this

std::string
A::print() const
{
   std::ostringstream oSS;
   copy(number.begin(),number.end(),
          std::ostream_iterator<int>(oSS,""));
    return oSS.str();
}

The later method avoids the convert to S construction that creates a number of stringstreams, and avoids having an explicit iterator. So is slightly more preferable to some peoples tastes.

Note: you have to add #include <iterator> , to your C++ file.

StuXYZ 731 Practically a Master Poster

Ok despite the code tags that you can (a) get from the advanced edit or simply just type them.

Templates:

Ok you need to remember the syntax of a class has not really changed.

e.g.

// Non-template class
class A
{
    void method();
};

void A::method() { return; }

// Template class [Template is added on top]
template<typename Item>
class B
{
    void method();
    void methodB() { return; } 
};

template<typename Item>
void B<Item>::method() { return; }

Note who you add the template part above each method and
as a tag to the class name. That tells the compiler that it is a general instance of B.

The remainder of your errors are basic typos and such. (I haven't run your code so you will have runtime errors I guess.)

StuXYZ 731 Practically a Master Poster

Well it is basically telling you that you have an old version of gcc.
(or a very new one that I haven't tested that has changed.)

If you write this:

// GIVES WARNING:
bool MyFunction(const double dist)
{
  if(dist < 1.2)
     return true;
  else if (dist>4.0)
    return false;
}

you get a warning (g++ version: 4.3.2)
Compiled with g++ -c -Wextra -Wall test.cpp BUT this doesn't give a waring

bool MyFunction(const double dist)
{
   if(dist < 1.2)
     return true;
  else 
     return false;
}

Note that the gcc does not do anything fancy to work out that the test has complete coverage (e.g if the second test was dist>1.0).

Give that you have not copied your code fragment from your test program, did you have an "else if" at the end?

StuXYZ 731 Practically a Master Poster

First off : The point of a vector is to know the order (otherwize use a set or list etc) .

Second : if you have a vector of pointer either :
(a) consider an autoptr/boost::shared_ptr [prefered] and just delete the element with a remove_if and then an erase e.g

std::vector<boost::shared_ptr<Obj> > Vec;
// ... populate etc
std::vector<boost::shared_ptr<Obj> >::iterator ec=
   remove_if(Vec.begin(),Vec.end(),
		boost::bind(&Vec:requiresDel,_1));
  Vec.erase(ec,Vec.end());

Now you might have a deletion that is more complex or depends on the index number. then try this:

std::vector<Obj*> Vec;
// ... populate here.
for(long int i=Vec.size()-1;i>=0;i--)
  {  
     if ( delRequied(Vec[i]) )
        {
           delete Vec[i]; 
           Vec.erase(Vec.begin()+i);
        }
  }

Note:
Normally I use size_t not long int but that has lead to confusion in the past.

StuXYZ 731 Practically a Master Poster

The problem is not within the code you have posted but rather within the code that call it. I guess you have something like this:

void draw(const Circle& A)
{
    A.SetSize(3,4,5);  // Discards constant!   
}
StuXYZ 731 Practically a Master Poster

The problem seem to be that when you get to Add(1,2,&x); . There is no way that the compiler can figure out what T2 should be.

So you can get round that by putting

Add<int,double>(1,2,&x);

or obviously, you can do it if you have something like

template <class T1>
void A::Add (int a,int b,T1 *passedVar1=T1(),
                 T1 *passedVar2=T1())
{}

// Then this compiles:
Add(1,2,&x);

along with appropiate declaration.

HOWEVER: Be VERY careful with this code since as you have written it you are going to get a segmentation fault if you try to access passedVar2.

StuXYZ 731 Practically a Master Poster

First use code tags.

Second the answer is LOTS and LOTS: including but not limited to

(a) putting using namespace std; , don't mistype
cont and cout.

(b) not considering what would happen if you enter -999

(c) Not considering that that you might not want to see all 100 numbers if you have only put in 2.

(d) not considering that there is a different between (a=b) and (a==b)

(e) not paying attention to the WARNINGS that your compiler is giving or using an old compile when a modern compiler is a download away.

(f) Not considering that std::cout<<2<<3<<std::endl; gives output of 23 Sorry for the slightly annoyed tone but RED letters and no code tags is kind of asking for it. However, if you fix those problems then it will be ok. BUT using a bubble sort with a sorted list each time is algorithmic madness.

I have just looked, this is your EIGHTH POST!!! Clearly you are beyond the ability to understand the written word so I guess none of this will help. If you want anymore help then please use code tags.

StuXYZ 731 Practically a Master Poster

Let me just add, since i is declared as a double , your loops are complete and test with i==1000 are complete junk.

If you add 1 to a double at about 1e16 this is true:

// True on some machine and about this value
double m=1e16;
if (m==m+1)
   std::cout<<"m+1 == m"<<std::endl;

Thus your inner loop will never exit.

StuXYZ 731 Practically a Master Poster

A multitude of errors, mostly caused by trying to write everything in on go.

(a) Patient includes an instance to Doctor. Therefore you must have a declaration of Doctor before Patient is declared. If it was just a reference or pointer you could have used a forward declaration e.g class Doctor; BUT you can't in this instance.

(b) Lots of typos. you use doc to mean doctor etc e.g. in the copy constructor for Patient. You write doctor1() in the main() { } section.

(c) Failure to call the base constructor in derived constructors and in the assignment operator.

(d) Lots of inconsitancy in format/layout which itself is not wrong but makes it difficult to see what is going on. For beginners I would recommend:
(i) Never use using namespace std; (ii) Don't put names of variables within declarations.
(iii) Consistent set/get naming so it is clear
(iv) copy Constructors are build like this e.g.

Doctor::Doctor(const Doctor& A) : Person(A),
  hour_fee(A.hour_fee),reg_num(A.reg_num)
{}

and the assignment operator like this

Doctor&
Doctor::Doctor(const Doctor& A)
{
   if (this!=&A)
     {
         Person::operator=(A);
         hour_fee=A.hour_fee;
         reg_num=A.reg_num;
     }
    return *this;
}

(v) Don't use a general protected, if that is what you have then change your model to a pure virtual inheritance.

(vi) Validate input.

esesili commented: it was very helpful +1
StuXYZ 731 Practically a Master Poster

You problem is scope. Let me walk through it even if you are familiar with it.

(a) If you want to use m in class X. All is ok.

(b) If you want to use m in class Y. Again all is ok, assuming Y does not define a local varaiant.

(c) If you wan to use m in Z. NOT OK. You would not have been confuse if you has done this:

class X
{ 
   public:
      static int Index;
   protected:
       int m;
};
class Y : public X
{
    void foo()
       {
           std::cout<<"m == "<<this->m<<std::endl;
       }
};

class Z
{
  void write
    { 
       //  Can't use X::m since there is no instance of X here.
      // Can use X::Index (as it is static)
      std::cout<<"Index == "<<X::Index<<std::endl;   
    }   
};

What you have done is defined Z within the scope of Y. That makes it no different to a general definition of Z as above BUT you are forbidden to use Z outside of the implimentation of Y. Therefore, you can only use static instance of X variables, or declare an instance of X and use that.

The only difference between my code and yours is that class Z has slightly larger scope. Unless you define an instance of Z within class Y, then there is no actual instance of Z to do anything with. You can have a whole array of Z if you like but you will have to add it to either a …

StuXYZ 731 Practically a Master Poster

Using gcc, #include <string.h> , provides a back-compatability system for stuff like using std::memcpy; etc...

You include that when you are using code that does not use the std::strcpy form but you want to just write strcpy(...) . Since you almost never want using namespace std; it is a nice half-way house, for importing c like code.

So if you have not included #include <string> , you have only a forward declaration for std::string. Hence the error. [Note that gcc use to include <string> in a lot of other includes, but they have been moving towards a independent #include system, so as you go up the version number you need to be more exact on you #include's. This means that although your code gets slightly longer your compile time goes down.

So in answer to the question you pose, yes you do need to add #include <string> BUT you may ALSO need #include <string.h>

StuXYZ 731 Practically a Master Poster

I think that you are after the distance algorithm e.g.

std::vector<int> A;
// ... stuff here
vector<int>::iterator i = find(A.begin(), A.end(), 9);
// can use std::vector<int>::difference_type 
// or static_cast to int etc.
long int index=std::distance(v.begin(),i);

Note it work with std::list and other containers with a reversible iterator.

The advantage is that distance works with list,map etc.

Some care has to be taken when using const_iterator, since you will need to case begin() and end() to the correct type. Which is a pain. [Normally cheat an implicitly cast by assignment e.g.

// long horrible way
long int x=std::distance(i,
       static_cast<std::vector<int>::const_iterator>(A.end()));
// other way
std::vector<int>::const_iterator ac,ec;
ec=A.end();
long int y = std::distance(ac,ec);
StuXYZ 731 Practically a Master Poster

Some comments:

First yes, one of the original ideas was to only write code once. (it was actually discussed in terms of macros but it still holds)

(b) #include <limits> gives the absolute best possible accuracy. This is not normally very useful for these type of problems. For example, you apply some matrix and quaternion rotations to some vectors, and you want to know if any are "equal". This will include several rounding errors, ie several epsilons. Yes you can determine the number, but normally there is an acceptable tolerance, but for say an eigenvector determination, is not really an option to determine the expected epsilon error from first principles, it is better to set a tolerance.

(c) Don't encode your equals in operator== as a class member. The key thing to note is the operator== does not take an additional parameter. It can only be retType operator==(inputType) {const};
were retType is any return type you like and inputType is any
input type you like BUT you only get one!. (const is optional)

Then because equal takes a number of different levels, e.g. at 1% or 0.0001% etc. Dependent on the instance. That also means you don't encode the tolerance as a static class variable. You then have to change it each call (and will forget).

I like the boost form boost::test_tools::close_at_tolerance<TYPE> and
boost::test_tools::percent_tolerance type forms
which are described http://www.boost.org/doc/libs/1_38_0/libs/test/doc/html/utf/testing-tools/floating_point_comparison.html and http://www.boost.org/doc/libs/1_35_0/libs/test/doc/components/test_tools/floating_point_comparison.html. The second reference is the implementation and the first is why …

StuXYZ 731 Practically a Master Poster

I normally think it is better to wrap these kind of fabs() type test
in a testing namespace , that provides a template form like this

namespace Approximate
{
template<typename T>
 bool equal(const T& A, const T& B,const double precision = 1e-4);

template<typename T>
bool notEqual(const T& A,const T& B,const double precision = 1e-4);

// less / greater etc.

}

Then specialize each type specifically. (that allows a 2/3 value comparison for vector, allows stuff like angles to remove the 360 degree phase invarient [e.g. 361 degrees is often the same as 1 degree]. Also for surfaces, it allows opposite normals to be considered the same (if sense doesn't matter).

This namespace then fits nicely into most testing framework, e.g. CppUnit.http://sourceforge.net/projects/cppunit/ and can be extended if you need to test base/derived classes etc.

Then the framework deals with about 95% of the stuff and you don't have to worry about writing another fabs(a-b)>epsilon and you have only done it once. Which was one of Strustrup's original tenants.

Note back: Normally you implement notEqual as !Equal BUT there are exceptions....

StuXYZ 731 Practically a Master Poster

Ok from your reply [paragraphs please!!] You haven't been that clear.
So I am going to guess what the problem is and what is in my opinion the optimal solution.

First : The difference between a a couple of template instances e.g.

class Image
{
   public:

        void setPixel(const int,const int,const RGB&);
        void setPixe(const int,const int,const Grey&); 
};

and

class Image
{
   public:

       template<typename T>
        void setPixel(const int,const int,const T&);
};

is relatively little. Both are resolved in the same way (assuming that you have instances, were T is RGB and T is Grey).

However, templates can be used for a return value.

class Image
{
        template<typename T>
        T getPixel(const int,const int) const;
};

but this is not acceptable C++

class Image           // BAD CODE:
{
    Grey getPixel(const int,const int) const;
    RGB getPixel(const int,const int) const; 
 };

So back to your problem, in producing an array you want the pixel type to be completely runtime specified, maybe in the array half are grey/ half are RGB (e.g. adding two images together). This is polymorphism. Produce a base class Pixel and specialize down to the RGB/Grey types using public inheritence. Make the destructors virtual and any other polymorphic functions, e.g. get/set/display etc.

You might have this

class Pixel
{ 
    public:
     virtual ~Pixel();
    virtual void display(Screen&) const =0;      // abstract class
};
class RGB : public Pixel
{
    public: 
       virtual ~RGB();
       virtual void display(Screen&)  const;
};
class Grey : public Pixel
{
public: …
StuXYZ 731 Practically a Master Poster

If you are writing a Pong game, I think that you are going to learn a lot, so well done.

Second AI in Pong is interesting, there are at least three models:

(a) pure deterministic. That is the computer calculates exactly where is wants to be and tries to go there. TWO things need to be calculated in this (i) the ball position and (ii) the humans bat position because (normally, the edges of the bat give different angles to the ball exit tragectory).

(b) Pseudo random. The computer plays with perfect play but the information has a random error. It is often better to have larger random error from based on the distance that the ball is from the computers bat. The exact weighting value between 0 and 1 (ie. completely random and perfect info) give an excellent human/computer game play. [Adjust the value on each won point/game]

(c) Use a neural network to determine the position that the computer bat should go to, this again, can give excellent results, but the neural network can but untrained after each win to give excellent human/computer playability.

Just some thoughts on stuff I have tried in a couple of game simulations [not actually pong but very close]

athlon32 commented: Thanks DUDE!!!! +1
StuXYZ 731 Practically a Master Poster

Depending on the problem use a template parameter. But the trick is to use a common base class.

Imagen this:

class pixelBase 
{
  // ... Stuff ...
  virtual void setPixel();
};

template<int pixelType>
class pixelItem : public pixelBase
{
    virtual void setPixel(...); 
};

This doesn't always give you the simplest architecture and you have to be careful that you are not better off with an abstract base class and two/more specialization classes.

I think that from your initial comment you are likely to not want the template solution but that is a guess.

Finally: What you do is have pointers to the base class e.g. pixelBase* displayArea[NX][NY]; Also I am assuming you know all the usual stuff about virtual destructors etc. If you are unsure, post some code and we normally review it. (sort of).

StuXYZ 731 Practically a Master Poster

Your zero's + poles are correct, your LCCD is incorrect as you have missed a term.

StuXYZ 731 Practically a Master Poster

This code is NOT fine. The problem is the there is not a copy constructor or an assignment operator. The requirement for using vectors SAFELY is that they work.

If you do not provide them, then the compiler uses a default version. Your class requires that you has std::string which ARE NOT simple objects. Therefore, when the default copy constructor runs which does a simple memory copy, you have trailing memory references. Therefore if you do things like remove an element and add a new element, or sort the vector all kinds of unexpected junk happens.

The effect of this is that this code is 100% unpredicatable.

Rules:

ALWAY provide a copy constructor and an assignment operator for ALL classes that have anything other than simple memory data. ie. all pointers, all complex classes. If in doubt provide one.

If you really really don't think you use one, then put a private definition.

Sorry for the rant. I wish the compilers gave much stronger warnings on this.

Additionally, please use some const, get functons are const, references that are only accessed are const etc.

Finally, do not use using namespace std; , that will get you into trouble later. you will acidentally overwrite string/vector etc. and not have the slightest clue what is going on.
It is slightly more typing but saves huge effort in debugging later.

Otherwize a worthy effort at your problem!

StuXYZ 731 Practically a Master Poster

Well types like int, float etc are fundermental, i.e. they are not classes. How the are converted into machine code requires examination of the compiler source code.

Types like ostream and string are part of the standard lib. So they are classes. This means that you can look at the standard headers and go from there. Normally they are full implemented in the standard header but it doesn't have to be the case.

If you use gcc you have the full source code for the compiler and you will see that std::ostream is implemented via

libstdc++-v3/include/ostream

and

libstdc++-v3/bits/include/ostream_insert.h

note that: file positoins are realative to the gcc directory. e.g.
/usr/local/gcc-4.3.3

Actually std::ostream is not that difficult to read. std::string is a bit more complex.


p.s. Please use descriptive titles in future, you are much more likely to get better answers.

StuXYZ 731 Practically a Master Poster

Your first followup question is explained on the page that you get by clicking on the first link I originally gave, the second, guess what it is explained on the page for the second, however, it isn't actually on the page I specified, you see there is a like called documentation.... :-O

Time to do the research that moves you from beginner to something else.

So if you look at the page you will see you need to read
Proceedings of the IEEE 93 (2), 216–231 (2005). Invited paper, Special Issue on Program Generation, Optimization, and Platform Adaptation. They kindly provide a pre-print.

Please read that then come back and ask about what you don't understand.

StuXYZ 731 Practically a Master Poster

Yes the GSL algorithms provide a colley-tukey FFT but as you know, this is requires the data set to be expanded to fit [tex]2^N[/tex] points. This is fine for short data sets but not ok, for longer data set or were a specific transform basis is required.

There exist a number of other transforms that work better in different radixs e.g 2,3,5, and 7. These are also in the GSL.

In addition there is Singleton's method for arbitary radix. Note that this is slow. [tex]O(N^2)[/tex]

FFTW provides an arbitary size transform at [tex]O(N log N)[/tex] which is obviously a great advantage for large N.

2D transforms

A higher dimensional transform of an array is in effect a transform of a 1D array with different/mixed stride. There are some tidy ways to process that. They come about in polynomial systems as you introduce more variables.

There are two ways of approaching FFTs. (a) number theory, very interesting but takes a lot of time to get to the working solution.
(b) knowing that you need an Fourier transform and using the libraries as black boxes. (well sort of).

The libraries referenced above will give you (b) and a lot of other stuff will give you (a). If you go down (b) then ensure that you always check solutions for numerical stability, normalization and profile your code.


Note: It is colley-tukey. [but look both up on the web] since it was John …

StuXYZ 731 Practically a Master Poster

Well the basic FFTs are available in the GSL (gnu-scientific lib.)
http://www.gnu.org/software/gsl/manual/html_node/Fast-Fourier-Transforms.html

If you are doing polynominals, you are very likely to need the complex form, and depending on exactly how you set it up the 2D form of that.

However, you should also look at FFTW3 http://www.fftw.org/ which is faster but slightly more complex to set up, it current supports a host of chip features which really helps. It is straighforward to do 2D etc. It handles the case of non-radix2 FFTs etc much better than GSL. [Note: This is possibly because I have taken more time to figure out FFTW3 than GSL and the last statement just shows my ignorance. :-( ]

Both of these are in C, but they are easy to wrap. To get really good low-level access you are going to need to write complex methods and at that point you library can be in any language you like, just add the data entry/exit parts, into a class.

If you get stuck post some code, I am sure many here use GSL and FFTW3.

StuXYZ 731 Practically a Master Poster

I really don't think that the problem is with string. Examining you code fragment, buffer2 obviously has size (you could test this with a std::cout<<"Length of buffer2 == "<<buffer2.length()<<std::endl; You haven't done something horrible like have your own local version of string ?? and then the horrific using namespace std; that everyone seems to add has caused you some problems. Basically you are going to need to look at your debugger.

StuXYZ 731 Practically a Master Poster

If you don't want to post your code, then maybe a cut down version. But the quickest way to do it yourself is to compile with debug info on and then run and wait till it crashes. The backtrace will tell you what memory component has been corrupted. It may take a little to work out what has actually happened as another array may have over writen it. The debugger can help listing the symbol and memory addresses.

You can also try valgrind. http://valgrind.org. Which finds memory errors/leaks etc. [with a few false positives.] This is also very good at finding array boundary errors.

Typical things you will find are memory that is assigned but not deleted. Memory that is created with new but deleted with free() and vis-vera. Array over runs. e.g

// runtime error
int A[10];
for(int i=0;i<=10;i++)
  A[i]=i;

etc.
Similar things happen in char* because people overwrite the end of the array. If all the warnings are not on then you can do this

// WRONG code:
char *A="Enter key"
std::cout<<"A == "<<A<<std::endl;
std::cin>>A;

This works if the entry is less than 9 characters long.

tux4life commented: Nice post, nice link :) +9
StuXYZ 731 Practically a Master Poster

Several things from your question:

First the string part. You have many options (a) you can indeed use
insert but the method requires an iterator to define the position for insertion. (b) the easiest to use simply += e.g

char p='x';
std::string A("test");
A+=x;
// A is now testx

Second :note your mistake in your function, you have used pl[0]
but it is a simple character. It is not an array.

Third: I don't understand why you have the variable winner. you assign a value to it and then return from the function. The means that the variable is immediately lost.
do this return 'M'; instead.

Also you claim to return an integer from find_player but you return a character. That is acceptable to the compile (with warnings) but unlikely to be the intent. Surely you wanted to return 0 if it is a draw and 1 if player one won and 2 (or maybe -1) if player 2 won.

Also, don't make a string and then compare, just use the individual result. e.g

// after test for p1,p2 only are s,r,p.
if (p1==p2)   // draw 
  return 0;
if (p1=='r')
   return (p2=='p') ? 2 : 1;
// .. etc

you might want a switch statement, you might also use a lookup table etc.

As for production code, I feel that you need a lot more experience getting code to work and compile before you even ask the question. Nobody checks …

StuXYZ 731 Practically a Master Poster

Quadratic multilication:

If you multiply two quadratics together you don't normally get another quadratic, (normally it is a quartic (x^4) ). What that really means is that quadratic(ness) should a property of a class, not itself a class. [Assuming that you are going to require multiplication]

So write a polynominal class and then has methods like bool isQuadratic() const or int order() const .
That makes everything lots easier.
e.g.

Poly& operator*=(const Poly&); 
Poly operator*(const Poly&) const;

I normally set a nice little problem with template<int NVariable> class Poly when I teach a C++ for scientists course. [ Poly<3> represents a polynominal in three variables e.g x,y,z ]

StuXYZ 731 Practically a Master Poster

First off, I agree that you should compile often.
Second: The main point, there are FAR too many fixed numbers.
e.g. "Round trip from Tokyo to Florida,America 2500$ per" That is horrific. Put

const double TokyoFloridaCost(2500);
const double YenDollarExchangeRate(14.3);

at the top of the code and use the variable. You can then use in all the places that you require it and if you need to change it then it is easy.

Also BE VERY careful about money in C++, I use a dedicated class, because you can charge someone 14.342 dollars (except in some very special cases) but often you need to keep track of the tiny bits e.g. 7% sales tax on 1.50dollar item is charged as 11cents but at the end of the day you give the tax man his fraction on total says to the nearest penny.

Additionally, I think your conversion are strange. I read your logic,
you tell the person the cost in dollars, ask if they want to convert it to yen and THEN ask them the number of dollars to convert?? JUST tell them how many yen 200 dollars is. Have a separte function to do just convertions if the customer can convert his currency.

Finally, why would a person.

StuXYZ 731 Practically a Master Poster

You can do this in a number of different ways. What you seem to have here is two processes to do, which have different efficient in different containers. That means that you have to have a compremise.

So, let use construct a simple consideration with the basic items:

You can use one of the assiociative containers e.g. set, map, these have the advantage of begin efficient to find items within the container BUT they do not preserve order, so although iteration from begin() to end() is guarenteed to (a) not repeat any of the items and (b) to contain all the items in the container the order is unpreserved.

Alternatively you could use a sequentual conatiner e.g. list or vector. The advantage is that it preserves the order but to search you need to step through the container.

Then there is the next decision, do you want store just strings or a composite class. So for example you could store a class like this

struct Node
{
     std::string Value;
     Node* PrevNode;
};

Finally, you can use TWO containers, e.g an set and a list. This double stores the informtion but makes life easy.
This would be used in a map (for example),

How to deside?

The key decision is which part of the problem is going to happen most.


\begin{tabular}{|l|ccc|}
\hline\\
Main/Job & Sequence & Assosiative &Two \\
\hline\\
Loop Over & X &&\\

StuXYZ 731 Practically a Master Poster

At a guess. I think that your problem is that you are using long, by itself, and not long int or long unsigned int , or long double etc.

Yes there is a fall back of long to long int, but does that still apply to long* and going to long int* ??

However, I don't have a windows system to test it but gcc casts long* to long int*. [linux].

StuXYZ 731 Practically a Master Poster

while you are fixing this. Please note that you often write

for (int count=0;count<customer;count++);
   {
      // Stuff
   }

Observe the semi colon after the for loop that should not be there since the body is not going to get executed until after the pointless loop. gcc gives warnings about this, as I expect every other modern compiler does, so please fix both errors AND warnings unless you are really absolutely certain the warnings are harmless. [Even then I fixe them to avoid output noise].

tux4life commented: Good observation! +8
StuXYZ 731 Practically a Master Poster

This is C++ not C, so I would have written:

b= -1*static_cast<int>(x)/2;

The main advantage of this is the you have an explicit bracket around the section you are casting and it is a BIG flag that you are changing type. Something that in numerical code is often such a big area of problems that the old (type) casts are often forbidden.

It also avoids nasty stuff when you convert (accidentally) from a pointer to a numeric type. Easily done when you have a long expression with pointers and multiplications.

StuXYZ 731 Practically a Master Poster

Well the problem seems to be that you expect the array to be terminated with a 0 . This is a mess.

What I think you have done is confuse the normal mechanism for strings e.g.

char* X="Fred";   // This gives    
// X[0]=='F' ... X[3]=='d' X[4]==0

with any other type of array.
e.g.

int X[]={1,2,3,4};
// X[3]==4, X[4] is undefined

But you really don't want to be using the last element of a float as a test value. (what would happen if say you used 0 and then one of your numbers was zero). So instead pass the size.

void displayArray( const float *aPtr,const int Size)
{
    for (int i=0;i<Size; i++ )
        cout <<aPtr[i] << endl;
}
StuXYZ 731 Practically a Master Poster

With that kind of error message I would be expecting that you have over or under run the array indexes.

If you post some more code, we can have a look.

But check that you don't let your indexes get to 400 or something.
(or negative!).

StuXYZ 731 Practically a Master Poster

This thread is getting a bit messy. So I am going to write a quick summary and how I would tackle the problem.

First: Coordinates are almost never integers, and once you have solved a 2d problem you often need a 3d solution, and sometimes higher dimensions.

What has been missed (I think), is a clear understanding of what can be done with coordinate transforms and vectors.

Considers a triangle defined by 3 points A, B ,C and each point
is A is (ax,ay) , B is (bx,by) etc...

Any linear translation or rotation or scaling, does not change the angle . For example triangle if you cut a triangle from paper and then drop it on your desk. You can rotate it any way you like cand you can place it anywhere you like and the angles don't change.

That relates to the problem in that you can translate the triangle to an origin. e.g after entering three points A,B,C as above, you shift the triangle by -A to get three new points which include the origin (0,0).

However, you can find the vector displacement that connects the points. For example, if you want to go from A to B, then you need to move (bx-ax,by-ay), likewize B to C is (cx-bx,cy-by) and going from C to A is (ax-cx,ay-cy), these vectors can be written as
[tex]\vec{AB}[/tex] etc.

For two vectors, the dot product is defined as.
[tex]\vec{A}.\vec{B}=|\vec{A}||\vec{B}|\cos(\theta)[/tex]

Nick Evan commented: Sounds like a plan! +17
StuXYZ 731 Practically a Master Poster

What is wrong with my sorting function? I am trying to put numbers in ascending numbers.

Nothing, in the fact that it actually works, BUT it is a bubble sort
and hence very inefficient.

If you are still having problems check your calling routine, are you
using an array followed by a count. Is that count correct?
e.g. I used this to test it.

int main()
{
  srand(time(0));
  int a[10];
  for(int i=0;i<10;i++)
    a[i]=rand() % 100;
  sort(a,10);
  for(int i=0;i<9;i++)
    {
      if (a[i+1]<a[i])
        {
      std::cout<<"Probem at i == "<<i<<std::endl;
      for(int i=0;i<10;i++)
        std::cout<<"A == "<<a[i]<<std::endl;
      return -1;
    }
    }
  return 0;
}
StuXYZ 731 Practically a Master Poster

Ok it is a singleton, so there are several methods, but teh stuff above doesn't look 100% ok.

First : if you are going to use a singleton you want to be 100% certain that there are no repeats.

That means that if you want to use the static pointer version you want this.

class Singleton
{
  private:

    Singleton();
    Singleton& opertaor=(const Singleton);
    Singleton(const Singleton);

 public:

    ~Singleton();        

    Singleton* Instance(); 
};

Note that you MUST put the copy constructor and assignment operator in the class definition because if you don't you get a default version AND that is public.

The advantage of the pointer version, is that creation is only needed in the case that you actually need it, and it naturally allows creatiion/deletion (with a bit of modification), as well as one of serveral models etc.

In multi-threaded case problem, it is the creation code that needs to be thread protected. Just lock on entry to creation.

StuXYZ 731 Practically a Master Poster

First of all, Narue's explaination is really well done (as usual).

Second, has ClockOwl noticed that REGARDLESS of the template issue
he has written the algorithm wrong and you get absolutely no items in x after kill_dupes is called you might as well write

template<typename T>
void kill_dupes(vector<T>& X)
{ 
    X.clear();
    return;
}

What you actual need I think --
is to change the test in the loop to

typename vector<T>::const_iterator it;
for(it = x.begin(); it != x.end(); it++)
   {
      if(find(y.begin(), y.end(), *it) == y.end())
	  y.push_back(*it);
   }

N.B. The iterator is out of the loop, too keep it looking nice on a web page.

StuXYZ 731 Practically a Master Poster

No the loop condition is correct.
Let us investigate:
Consider my original code with the following, slight changes

int deckIndex[52];
int deck[52];
// ADD THIS BIT:
for(int i=0;i<52;i++)
   deck[i]=100;
// AS before
for(int i=0;i<52;i++)
   deckIndex[i]=i;

// as you suggest
for(int i=52;i>1;i--)
  {
      const int X=rand() % i;
      deck[i-1]=deckIndex[X];
      deckIndex[X]=deckIndex[i-1];
   }

// Add this:
std::cout<<"deck[0] == "<<deck[0]<<std::endl;

Now as you see deck[0] is unfortunately 100, that is definately incorrect. Hence I feel that you much have i>= 1 (or i>0) but not i>1.

However, you can write this:

for(int i=52;i>1;i--)
  {
     const int X=rand() % i;
      deck[i-1]=deckIndex[X];
      deckIndex[X]=deckIndex[i-1];
   }
deck[0]=deckIndex[0];

which is much better than the code I gave.

p.s. In my previous post the numbers 2.55 was for the sum of the first 5 cards in the deck and the sum 2.45 was for the last 5 cards. The text was not clear. There is a bigger difference to the expected mean of 0.5*N , where N is the number extracted from the deck as N tends to 1. I can see how to write the solution to the general case (I think) but haven't put the effort in to do so.

StuXYZ 731 Practically a Master Poster

First : As pointed out there are vectors of vectors. That is ok.
But often you want a 2d array, i.e each column is the same length.
So try the boost::multi_array. Lots better.

Second : you can do what you want with pointers/new/delete etc BUT you have to get it right:

You have

// CODE WITH ERROR:
 windarray = new string *[rowcounter];
windarray[rowcounter]= new string [colcounter];

That is a memory violation since you correctly allocate rowcounter pointers to point to the string giving you an array of [0 to rowcounter-1] but THEN allocate to rowcounter....

You need this:

windarray = new string *[rowcounter];
windarray[0]= new string [rowcounter*colcounter];
for(int i=1;i<rowcounter;i++)
   windarray[i]=windarray[0]+colcounter*i;

NOTE: to delete do this

delete [] windarray[0];
delete [] windarray;

There are other versions of this and you should keep in mind that you can't mix and match creation forms and delete forms.

Finally, please layout your code with more consistent line breaks it will make it much easier for you to read/debug/learn from/deal with in 2 years time. E.g put each for loop on a new line, and then indent. But whatever you choose BE CONSISTENT.