mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To elaborate a bit more. Your data member "empID" will have its destructor implicitly called when your object of class "heap" gets destroyed. And since std::vector will release all its memory in its destructor, there is nothing you need to do in your destructor (it is all done implicitly, that's the magic of RAII).

By opposition, if you have a dynamically allocated array that you hold with a pointer, then you would need the "delete[] ptr;" in your destructor because the destructor for pointer types does nothing to release the pointed-to memory (in fact the destructor for any primitive type is empty).

In that sense, STL containers are very safe when it comes to preventing memory leaks. In fact, if you use only RAII components, then the memory management coding-efforts are greatly reduced (and virtually all class-destructors turn out to be empty or omitted).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I'm only going to show you how to implement the processHandle in RAII, the others are for you to do in a similar fashion. You simply wrap the processHandle in a private struct (if you don't need to reuse this struct's code somewhere else in your library). Then, you load the process in its constructor. If it throws, then it will not try to free the process handle, but if it was successfully constructed, it will get destroyed and will free its processHandle upon destruction. That can be done as follows:

class DllInjection
{
  private:
    std::wstring dllName;
    
    
    struct ProcessHandleImpl {
      HANDLE processHandle; 
      DWORD processID;
      std::wstring processName;
      ProcessHandleImpl(const std::wstring& aProcessName);
      ~ProcessHandleImpl();

      void isValidProcess(const std::wstring& aProcessName);
    };
    ProcessHandleImpl processHdl;

    LPVOID memoryAddress;

    void isValidDll(const std::wstring& dllName);

  public:
    DllInjection(const std::wstring&,const std::wstring&);
    ~DllInjection();
    void injectCode();
    void unInjectCode();
};


DllInjection::ProcessHandleImpl::ProcessHandleImpl(const std::wstring& aProcessName) : processHandle(0), processID(/* ??? */), processName(aProcessName) {
  isValidProcess(processName);

  if ((processHandle = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ,0,processID)) == NULL)
    throw InjectionException(GetLastError());
};

DllInjection::ProcessHandleImpl::~ProcessHandleImpl() {
  if(processHandle) //this check is not really necessary because processHandle is always non-NULL if the constructor succeeded.
    CloseHandle(processHandle);
};


DllInjection::DllInjection(const std::wstring& processName,const std::wstring& dllName) : processHdl(processName)
{
  isValidDll(dllName);

  this->dllName = dllName;
  memoryAddress = NULL;
  injectCode();	
}

void DllInjection::injectCode()
{
  if ((memoryAddress = VirtualAllocEx(processHdl.processHandle,NULL,wcslen(dllName.c_str()),MEM_COMMIT,PAGE_READWRITE)) == NULL)
    throw InjectionException(GetLastError());
  if ((WriteProcessMemory(processHdl.processHandle, memoryAddress, dllName.c_str(),sizeof(dllName),NULL)) == 0)
    throw InjectionException(GetLastError());
  _LoadLibraryEx procAdd = (_LoadLibraryEx)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryEx");
  if ((CreateRemoteThread(processHdl.processHandle, NULL, 0, (LPTHREAD_START_ROUTINE)procAdd, (LPVOID)memoryAddress, 0, NULL)) == NULL)
    throw InjectionException(GetLastError());
  return;
}

The others can be done in a similar fashion.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

That's very easy actually. In order of simplicity:

1. You can use the function glFrustum() which takes left, right, bottom, top, near and far coordinates for the projection, all centered about the vanishing point. So if top and bottom are not equal in magnitude (like 1 and -1) then the vanishing point won't be in the middle. Essentially, the typical gluPerspective function is just a specific case for which top = -bottom and left = -right, in which case only the aspect ratio and FOV matters.

2. You can follow the following explanation of projection matrices to manually set the projection matrix yourself. The format of all matrices in OpenGL is a 4x4 matrix (column-major, meaning that columns are saved one after the other in a linear array of length 16). You would pass the matrix that you have computed as follows:

GLfloat myProjectionMatrix[16];
  //calculate myProjectionMatrix based on the link above.
  glMatrixMode(GL_PROJECTION);
  glLoadMatrixf(myProjectionMatrix);

3. If you want a slightly different effect, you can also apply are translation (in x-y) after the perspective calculation, as follows:

glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glPerspective(/*.. your fov, width / height, near and far data here ..*/);
  glTranslatef(0.0, -0.25, 0.0);

Happy Coding! ;)

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

So far, I think all the above answers are very good and have all the essential ideas. One additional guideline I can think of is about preserving interfaces (but probably doesn't concern you too much at this point, it's more for bigger projects). There are programming techniques such as some forms of Cheshire cats (i.e. the PImpl idiom) and binary compatible interfaces that have more strict requirements for what can go in the header files (or at least the published headers). Basically, the more code / complications you put in your header file, the more likely it is that you might have to fix a problem with it later, and then you "break" the interface, often requiring or at least triggering global recompilations (which are extremely annoying in big projects!).

One caveat:
From Tellalca:>>Btw you cannot seperate the implementation and the decleration if you are working with a template class.
I have to disagree with that. First off, yes, you can separate implementation from declaration of class or function templates (made possible by either explicit instantiations or including .cpp files). Second, it is a good idea to do so for all the same reasons that apply to "plain" code, however, people typically accept more code in a header file for a class template if it is simple enough. In other words:
In plain code, only the very trivial functions can (and probably should) be implemented in the header file, while the rest is in the cpp.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I can see a few problems:
1. You don't delete the nodes that you pop, that is a memory leak.
2. I don't see a default constructor that sets the initial value of "tos" to NULL, if that is not done, it will surely lead to a segmentation fault if you try to pop more elements than there are on your stack (and based on the logic of your math operation inversion, that could certainly happen).
3. The function isFull is really quite useless.

You should probably use a debugger for this, with breakpoints and stack inspectors, you should find this error very easily by stepping through the code.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you ran out of stack memory, that is probably with your recursive implementation. The rule is that if you write a recursive function for which you expect very deep recursion (like 500 recursive calls), then you should really minimize the number of local variables in the recursive function definition. Also, using the highest level of optimization as a compiler option ("-O3" for gcc or MinGW) can help as well. But first, look at the algorithm itself, please post what you have if you want any more specific help/hints from us.

alaa sam commented: Thanks for help +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Welcome!

I also hope you have solved the problem already, but it won't be from the help of the previous answers (sorry guys).

What you need to do is loop until you hit the end of the file. The end-of-file is found by simply using "inputFile.eof()". It returns true if you are at the end of the file. So your reading loop should look like:

//Read numbers from file into the array
for(count = 0; count < SIZE && !inputFile.eof(); count++)
  inputFile >> scores[count];

That's it that's all! Enjoy!

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well I'm certainly curious to see if a linear time algorithm exists, can't think of any.

As a starter, I can think of a few basic methods:
- Brute force: pick each element of A and do a linear search for its match in B. If a match is found, then the sets are not disjoint. If the complete search doesn't yield a match, the sets are disjoint. That would be essentially O(n^2) in time.
- Sort and search: sort both arrays, in O(nlog(n)) time, and then progress through both A and B at the same time to look for matches, in O(n) time. Overall that would be O(nlog(n)) still.
- Joint and sort: treat both sets as one big set and sort the set while looking for duplicates (assuming there are no duplicates in the original sets A and B). That would still be O(nlog(n)).

Any other suggestions?

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

***PLEASE USE CODE TAGS IN THE FUTURE***

Your problem is classic. You should know that the pthread_cond_wait function is subject to spurious wake-ups. This means that sometimes (fairly often actually), the pthread_cond_wait function will return even when the condition was not signaled. You need to use a predicate. This means, each condition should be accompanied with a status variable (like a bool or int) that is set to a particular value anytime the condition is signaled. Then, you wrap the pthread_cond_wait inside a while loop that checks the predicate every time pthread_cond_wait returns, to make sure that you only continue after the loop if the predicate is met, meaning that the condition was actually met and that it was not a spurious wake-up.

As for the hung-ups you are getting, I'm not entirely sure that is completely attributable to spurious wake-ups (but certainly to some extent). You might have a dead-lock too. Essentially, spurious wake-ups might cause a desynchronization of the threads. What happens is that one of your working thread is waiting for the "start" signal, while the main thread is waiting for "all-finished" signal, which will never come. How this comes about is so:
- A working thread has a spurious wake-up while the others are waiting (start not signaled yet)
- The working thread does its work and increments nCount (which becomes 5)
- The main thread signals start and sets nCount to zero
- When all working threads are back …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Don't give up. It is easy to do this as long as you stay away from Microsoft products (you are experiencing their tactics of giving away the Express version to sucker people into buying the full version.. just like a pill-pusher).

You said you have Borland... is this Borland C++Builder 5? If it is, all you need to do is click New Project -> VCL Application -> New Form ..something like that. Then you will get a blank Windows' form. Then you can put onto the form a component called TChart that you will find in one of the panels of the component library. Put the TChart on the form, scale it to the size you like, double-click on it and change the settings to customize it. Then click on the form again, see "events" in the object inspector, find the event called "OnShow", double-click in the white space next to it, you will be directed to any empty function called OnShow() and add the code to plot your graph there (to add points, it is something like myChart->AddXYPair(), but I'm not sure). But handing in code that only works for Borland C++Builder and the VCL is probably not the best thing.

Alternatively, you can use SDL with SDL_draw. Which is going to be easy and much better than graphics.h or anything of the like. You can create a window of the size you like and draw whatever your imagination can produce.

If …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

**Please use code tags in the future**

First, one little thing that often comes up, your GetNumber function should include a "cin.ignore();" call to clean the input buffer after entering a numeric value of any kind. So it should be:

void GetNumber( )
{
  cin >> reco.Dlicense;
  cin.ignore();
}

Now, the biggest problem is your SaveDB function. It is so wrong that I can't really make much sense of it. But I know it is wrong for several reasons:

void Tbuiltdoc::SaveDB(Record *rec)
{
  NodePtr newNodePtr = rec; //you set newNodePtr to rec here, but then..

  newNodePtr = new Record; // you give it another value which is a pointer to a new record.
  currentPtr = newNodePtr; // then you sen currentPtr to that same new record.

  ofstream ofs(fn, ios::binary | ios::app);
  if(!ofs) 
    cout<<"error";
  ofs.write((const char*) rec, sizeof(Record)); //this is very wrong, you need to save the individual components because rec contains pointers.. the addresses will be saved in the file and will be completely meaningless when you load it again.
  ofs.close();
  if(first != 0) //What is the value of first.. should it not be "head"
    head = currentPtr; //if first record
  currentPtr = currentPtr->Link; //at this point, currentPtr points to an uninitialized record, and Link is a garbage value.
  delete newNodePtr; //now you delete newNodePtr, which is OK because newNodePtr has always been meaningless to start with, but normally it should be a new link in the list and should not be deleted but kept in the …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First, the prototype for selectionSort should match the definition EXACTLY, always. So, this will rectify it:

void selectionSort(int a[], int size); //and you should place it outside and before main()

The reason why the compiler doesn't care is because the compiler won't see a difference between two function prototypes if only the result type differs. But at run-time, the resulting value will be garbage (NaN, or any "random" number).

Second, this piece of code:

double results;
    
    for( int i(0); i < N; i++){
         
         results = array[i];
    }

has absolutely no effect what-so-ever. Was there something you expected this snippet of code to accomplish? If yes, tell us, so that we can clarify it for you.

Finally, your selection sort algorithm seems totally fine, but notice that what you are doing is overwriting the values in the array called "array" that is passed to the function, so the final resulting array can be printed to the screen by looping in that array and printing each value. So, if you thought that printing the result of selectionSort was going to print the array in the correct order, you were mistaken.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The problem is that you are updating the screen only when an event comes. So if you move the mouse, you trigger a bunch of unhandled mouse_move events that also makes your screen get updated. You should move the group of lines that perform the move, applysurface, show, and SDL_flip, outside the event loop into the "still-playing" loop, i.e. spela. You might want to add a timing to the loop such that you don't get 100% usage of the CPU. SDL provides timers for that.

Lycka till.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The const keyword only controls whether you can modify the object or not. There are two kinds of access: read and write. Const just forbids the write access but, with friendship, you still have read access to private members. Generally, if a function does not need to modify the object(s), it should have const qualifiers.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

At line 35, you need parentheses to enclose "denominator1*denominator2" like you did at like 42.

As for the main problem, lines 53 to 56 are very wrong. There is absolutely no relationship between sum_result in main() and sum_result in add_fractions(). These are two completely unrelated variables. The fact that they have the same name does not make them have the same value. In any case, the function add_fractions and multiply_fractions are never called anywhere, why would you even expect that the sum or product has even been computed anywhere. To fix the problem, you could do this:

sum = f1.add_fractions(sum_result);    //call member function
    cout << "The sum of the two fractions are  " << sum << endl;
    product = f1.multiply_fractions(product_result);   //call member function
    cout << "The product of the two fractions are " << product << endl;

But you should also realize that the parameters to the function add_fractions and multiply_fractions are useless (they are input parameters without meaningful values). You should make those two functions to not take any parameter.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Aside from what AD proposed, there are all the modifiers in the std::vector class:
- assign() : overwrite the content of the vector from either a constant or another iterator pair (begin,end).
- push_back() : add an element at the end.
- pop_back() : subtract the last element.
- insert() : add an element or many elements just before a particular position.
- erase() : erase an element or many elements.
- swap() : swap the content of one vector with another.
- clear() : erase all the elements.

There are also a plethora of possibilities under the <algorithm> header. Many of these can be even more useful in combination with the back_inserter for example.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The important lines would be something like this:

cmake_minimum_required (VERSION 2.6)

add_executable(demo "x04.cc")

find_library(PLPLOT_LIB NAMES plplotcxxd PATHS "/usr/lib/") #or some other path
if(NOT PLPLOT)
  message(FATAL_ERROR "PlPlot library is missing")
endif()

target_link_library(demo ${PLPLOT})

Note that you should probably follow a cmake tutorial because there are many more things you might want to do with cmake, link specify an include directory(ies), specify installation paths for targets, libraries and headers, include sub-directories with other CMakeLists.txt files, etc. etc.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have to make sure that the mixBreed() function is always declared with the same prototype. And in this case, const makes sense and it probably should stay.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You can throw any exception to like, if you have a specific purpose that doesn't fit in the standard exceptions, then make your own:

#include <exception>

class InvalidProcessException : public std::exception {
  private:
    std::wstring message;
  public:
    InvalidProcessException(const std::wstring& aProcessName,const std::wstring& aDllName) : message("Invalid Process Exception with process name '" + aProcessName + "' for dll name '" + aDllName + "'!") { };
    const char* what() const throw() {
      return message.c_str();
    };
};

myclass::myclass(const std::wstring& processName,const std::wstring& dllName) throw(InvalidProcessException) //it is always good to announce what exception you might throw from this function.
{
  if ( (isValidDll(fileName)) && (isValidProcess(processName)) )
  {
    this->dllName = dllName;                                     
    this->processName = processName;
    memoryAddress = NULL;

  }
  else
    throw InvalidProcessException(processName,dllName); //throw your specific exception.
  }
}
lochnessmonster commented: thank you makes sense! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I see no syntax problem with this code.. have you tried compiling it?

The only problem is that you are using friendship relation for a pretty trivial purpose. What is wrong with a simple getHeight() member function in both classes, or better yet as a virtual method in the Dog class. The problem with your code is mainly that what if you have a third, fourth, fifth, .. tenth breed of dog.. how many versions of mixBreed() will you have to implement. You can see that it is not an easily scalable design (mainly because you introduce a coupling between the classes Alsatian and Retriever when these classes are not related (the Alsatian breed of dog has no need for the Retriever breed of dog to exist), don't introduce dependencies that don't make sense, they will haunt you later).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

In my problem, the main factor that affects the accuracy is not the physical error it is really the rounding error.

But in general it is very hard to say that the rounding error is negligible,
if you cannot handle it, and you dont know its value at the end of your calculation. I think nobody can prove mathematically that the rounding error is not important, in a difficult numeric algorithm. Usually there is an acurracy parameter in your calculation, and the decreasing of this parameter means better estimation, but you cannot decrease it without bound. Usually you cannot know this bound (without precise error handling) you just feel it, but sometimes you are wrong.

As arkoenig said, I would also be interested in some details on your problem that is _really_ only affected by ROE.

You said: "nobody can prove mathematically that the rounding error is not important"... If you have never encountered those types of proofs I wander what you are doing tackling a numerical method problem in the first place. You can certainly infer upon the amplification of the round-off error in an algorithm, you can do a best and worst case analysis, the best case is when no ROE is assuming all calculations are exact throughout the entire algorithm and the worst case is when all calculations suffer maximum round-off error. In my experience of the few cases and proofs I have seen, these two numbers wind up incredibly close to each other for …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is too much code for me to look at... but just a quick run through your findPath() function shows that you have no return statement after a recursive call. Normally, you would use the result of the recursive call to either return it directly or use it to compute the returned value. You are doing neither of those things. I don't understand why your compiler allows this (you should turn on all the warnings, and if you get something like "function xxxx might not return any value", then you have a problem, and in this case, you have a problem either way).

BTW: it doesn't seem like a recursion is a particularly good idea here... usually a large number of parameters is a sign that recursion might not be the best alternative.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I remembered answering a similar post before here, but then I realized you (merse) were also the OP for that thread. I guess you are obsessed with this topic... If what your are looking for is top speed and perfect accuracy, you just moved beyond obsession.. into fanatical idealism. In the real world (or should I say, in the double world, lol!), there is always going to be a trade-off between accuracy and speed / memory usage. You can't have both extremes, you have to choose your spot. The standard IEEE floating-point arithmetic and representation of real numbers is a good equilibrium for most purposes. Game programmers and others want fast calculation and don't care about accuracy at all, while physicists want very precise results but don't mind having to wait for quite a while for their results (or they have fancy super-computers), while engineers, like me, want reliable results but not necessarily extremely accurate (there are always large safety margins applied anyways) and are very impatient (nobody likes numerical simulations that take more than a few days).

Remember also that the main factor that affects the accuracy of the output of an operation is the accuracy of your input values. And by accuracy, I mean, of course, not the round-off-error of the double variable, but the error in the value you provide. Say, I want to simulate a mass-spring dynamics system, then, the results depend very much on how accurate the values of mass, stiffness, and …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Just abandon the CLR part. .NET and all this C# and managed C++ is useless and cumbersome. If your problem would have been just in straight C++, it would have been solved in minutes (using Boost.Thread), but only because of marshalling stuff and the evil .NET platform, you are stuck... another case of downsides outweighing the upsides in managed programming languages.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The way you set up your addition function, it will add the value of the parameter to "this" object, so you don't need the assignment at all, or you need to redefine the implementation. This line:

x = c.addition(d);

actually adds d to c and stores the result in c, like if you did "c += d;". So the result of the operation is then stored in c and that's it. The reason why you get this compilation error (not an exception btw) is that your function addition does not return anything (void return type). It is not possible to assign nothing to something. If you want your addition function to behave like "x = c + d;", you would need something like this:

//In Rational.h

class Rational {
  public:
    Rational(int num = 1, int denom = 2); //Default constructor
    Rational addition(Rational); //notice the return type Rational.
    //other functions

  private:
    int numerator;
    int denominator;
};

//In Rational.cpp, constructor

Rational::Rational(int x, int y)
{
	numerator = x;
	denominator = y;
}

Rational Rational::addition(Rational f)
{
   //Add numerators and denominators
   return Rational(numerator + f.GetNumerator(), denominator + f.GetDenominator());
}

int main()
{
  Rational c( 2, 6 ), d( 7, 8 ), x; // creates three rational objects 

  x = c.addition( d ); // adds object c and d; sets the value to x

  return 0;
};

As Fbody said, your addition function is of course not correct, but this should get you going.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you want to access the data member from another class or function specifically, you can use the "friend" keyword, as such:

#include <iostream>

class Bar; //forward declaration

class Foo {
  public:
    void someMethod(const Bar& a);
};

class Bar {
  private:
    int x;
  public:
    Bar(int aX) : x(aX) { };

    friend class Foo; //declare Foo as friend, granting access to private members
};

void Foo::someMethod(const Bar& a) {
  std::cout << a.x << std::endl;
};

int main() {
  Foo f;
  Bar b(10);
  f.someMethod(b);
  return 0;
};

But generally, friend relationships are an indication of bad software design, i.e., poor separation of the purpose of the different classes/objects.

You can also avoid the ugly accessor functions (get and set) with simple constness:

class Bar {
  private:
    int x;
  public:
    Bar(int aX) : x(aX) { };

    int X() const { return x; }; //provide read-only access to x.
    int& X() { return x; }; //provide read-write access to x.
};

But, in the above case, you would just be better off making x a public member (there is nothing wrong with doing that if it makes sense for your application to expose x).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First, you have an excess semi-colon in the for-loop line, this will actually cause the loop to do nothing and try to dereference the end iterator (possibly a segmentation fault or access violation). The line should be:

for ( it = file_user.begin() ; it != file_user.end(); it++ ) //notice no ; at the end.

The error message you get is weird to me, it should work fine. Quick fix, just use this line instead:

cout << it->c_str() << " " ;

This will get the char* version of the string (which is the same type as "" literal strings, which already work in your example).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have three places (line 20, 31 and 32) where you do something like this:

contributors * thePatrons = new contributors [];

I have no clue why your compiler allows this or into what it gets compiled.. I just know that it is wrong (or at least very weird). You cannot allocate an undetermined amount of memory (which is what the [] means for static arrays), that simply makes no sense. Do as Ancient Dragon suggested.

Also, I find your use of ignore with those arguments a bit unusual, why not use just the normal "cin.ignore();"? If it doesn't work, and considering that your compiler will actually compile something like "int* ptr = new int[];", it makes me think there might be something fishy going on with your compiler / IDE. I compiled your code and it works as it should (with the size given for the allocated arrays).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As FBody said, of course, you need to match the function declaration in the cpp file to take a Date as second parameter instead of three ints. Then, it should work. Just in case you previously changed it to three ints because you had trouble creating a patient object, here is how:

class Patient {
//...
    Patient(string, Date);
//...
};

int main() {
  Patient p1("roger",Date(11,11,2010));
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You are right, the variable will wrap around to its highest value. The only way that I know of to avoid it is to do the following:

unsigned int num = 0;

num = (num < 1 ? 0 : num - 1);
cout << num;
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Usually if it makes sense to you, it will make sense to others, given the proper documentation. Whether your code is to be published or not does not make a difference because you should always write your code as if it was to be published. Put care into thinking about solutions to your problem. Composition is generally good practice and most programmers are very accustomed to it, and it is often the better alternative compared to multiple inheritance or semantically ill-conceived class hierarchies. Often, when composition is useful, generic policy classes are an even better alternative (look up the subject). Also, it is a good idea to provide a default composition if it makes sense to do so, it will ease the "typical" user's burden.

Remember that you never know when you might come back around, much later, and look at your own code and try to understand what you did or how to reuse it. So, I always say, there is little difference between another programmer and your-future-self. So, whether you want to publish the code or not, you still want to organize it and to document it properly. But no need to go crazy with the documentation, you don't need to have like a comment for every line of code. Mostly, the best thing is to just give a good clear (doxygen) comment block to each function you have (with all the tags filled, like: \pre, \post, \param, \return, \author, \date, \throw, \test, \todo, etc.). That also …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you want to keep the sum function template as is, you can also use the following code which uses the conversion operator (operator int()):

#include <iostream>
 
 class Homework
 {
   int time;
   
   public:
     void SetTime(int t) { time = t; }
     explicit Homework(int t) : time(t) { }; //add an explicit constructor with int.
     int operator int() const { return time; }; //add a conversion operator to int.
     int operator+ (const Homework& rhs) const;
 };
 
template <class T>
T sum (const T& a, const T& b) {
  T result = T(a+b); //make the result explicitly converted to T, in case the + operator does not already output a T object.
  return result;
}

//lhs.time + rhs.time = int result

int Homework::operator+ (const Homework& rhs) const {
    int a = this->time;
    int b = rhs.time;
    int result  = (a+b);
    return result;
}

int main(int argc, char *argv[])
{
  Homework hw1(1);
  
  Homework hw2(2);
  
  {
  int total = hw1 + hw2; 
  std::cout << total << std::endl; 
  }
  
  int total = sum(hw1, hw2); //no need for the explicit template argument here.
  std::cout << total << std::endl; 

  return 0;
}

This way, the sum function template could also be used for float or double, not just types that add up to an integer result.

brandonrunyon commented: awesome example! did not think to use conversions... +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>can I say "In theory, the copy constructor is called. However, a non-copy constructor is called depends on the compiler"?

I really don't like the sound of that, but loosely speaking it is alright. More precisely I would say, for "D d1 = D(23);", that:
Syntactically, the copy-constructor is called to initialize d1 with the temporary "D(23)".
Semantically, 23 is explicitly converted to class D and assigned to d1.
Effectively, only the persistent result of the expression is guaranteed by the compiler, that is: d1 is guaranteed to hold the value 23 after this line.
In practice, the end result of what gets executed for that line is compile dependent and thus, any assumptions about what happens, other than the persistent result or effect mentioned above, are to be avoided if the code is to be well-behaved.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

"make" is one of the most common build tool for all medium to large scale programs. They don't give the instructions on it because very few programmers who go out to get Qt creator are not already very familiar with "make". And if you are a *nix user, that is a very common way to install software.

What you need to do (assuming you are under Linux), is go (in the terminal) to the folder in which you extracted the downloaded package, type "make" (if you downloaded the source files), then "make install", and you are done (NB: don't type in the quotation marks, of course). You can most probably also get it directly from the package repository with aptitude, with the following command (from any location, but from the terminal): "sudo apt-get install qtcreator", type in your password, and you're done.

If you are under windows, well, I'm sure the installer is a normal one (next, next, next... finished buttons!).

Of course, you need a compiler installed on your computer! Linux: gcc (install with "sudo apt-get install build-essentials") or Windows: MinGW

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I expect the copy constructor should be called after the temp object is created.
>>But why no "copy" is displayed?
Because the second line "D d1 = D(23);" is an explicit conversion. One way to look at it is in terms of optimization, that is, this is a trivial case where any compiler will understand that it is a waste to create a temporary D object and then assign-to or copy-construct object d1, it will optimize it away and simply call default D(int) constructor. Another way to look at it is in terms of semantics, that is, you can see this syntax as a way to make the intention to convert the integer value to a class D very clear and unambiguous (this is the purpose of the "explicit" keyword, to disable unintentional conversions). Essentially, if the compiler sees that the left-hand-side is a non-initialized object, it will try its best to find a constructor call in the right-hand-side that it can perform in-place instead of the default constructor call plus the assignment operator call.

As a rule of thumb, I would say that there is quite a bit of freedom given to the compiler when it comes to constructing objects (especially when temporaries are involved), unless you give it more specific instructions. This is why a particular sequence of constructor calls should never be a critical functional mechanism in your code (unless the construction/destruction is controlled more closely, e.g. in idioms such as factory-functions, non-copyable and …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@ffej2ffej:
If you don't mind OOP and pointers, I would recommend Qt (it is easy, cross-platform, and comes with very decent, lightweight IDEs for windows, Mac and Linux).

@OP:
Just use SDL (Simple Directmedia Layer). It is not object-oriented at all (essentially a C library), has those good'ol' fashion handles and stuff instead of pointers. It is essentially has features similar to the win32 API, but for any platform (but you don't get any GUI elements really, although I'm sure there are plenty of add-on libraries that have buttons and menus and stuff).
But I would encourage you to face your fear of OOP and save yourself the trouble of trying to develop a GUI for your application in procedural programming (it will be a nightmare for you..). GUI programming is one of the prime applications where OOP makes a hell of a lot of sense (as opposed to other applications like numerical analysis where it still makes sense, but to a lesser degree).

Stefano Mtangoo commented: Well said +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think that Boost.Thread is by far the easiest solution (I'm not sure how well it is usable on Solaris, but I presume it is alright.. at leas the latest version).

Here is how I would do it:

#include <boost/thread.hpp>

class MyClass {
  //blablabla
  //need to provide a copy-constructor and assignment operator.
  //and make it callable, with operator () :
  public:
    void operator()() {
      //do your stuff here...
    };
};

int main() {

  while (true) {
    boost::thread daily_processing(MyClass(/* some params */));
    //...
    //do all the other stuff your program does.
    //...
    //check if the daily processing is done, if not, join it to the main thread.
    if(daily_processing.joinable()) 
      daily_processing.join();
  };
  
};

In the above example, the object of class MyClass will be copied once into the internal storage of the boost::thread object. If MyClass is large or a singleton or you want it to persist through the entire application's lifetime (not just for the life-time of the thread), then here is an alternative:

#include <boost/thread.hpp>

class MyClass {
  //blablabla
  //no need to provide a copy-constructor or assignment operator (although, you should either disable them (boost::noncopyable) or provide them).
  //provide a callable nested functor:
  public:
    struct daily_process_functor {
      MyClass& parent;
      daily_process_functor(MyClass& aParent) : parent(aParent) { };
      daily_process_functor(const daily_process_functor& aObj) : parent(aObj.parent) { };
      void operator()() {
        //do your stuff here... using parent.methodName(); 
        //or.. you also have access to private members of MyClass to do everything here.
      };
    };
};

int main() {

  MyClass data; //you have a …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are just a few mistakes (proper indentation helps to see these mistakes):

char large(char *p,int a)
{
  int large=0,x=0,b; //x should start at zero.
  char r;

  for (int i=0;i<a;i++)
  {
    for(int j=0;j<a;j++)
    {
      if(*(p+j)==*(p+i)) //notice the difference here *(p+i) instead of *p+i, and the i != j is not necessary.
      {
        x++;
      }
    } //end the inner loop here
    if (x>large)
    {
      large=x;
      b=i;
    }
    x=0;
  }


  r=*(p+b);
  return r;
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think you should make all those data members under the "protected" scope instead of "private", that would solve all your problems.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Between line 17 and 18, add the following:

first = NULL;
	last = NULL;
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I would recommend that you simply comment out all the code in main() and put the lines back in one at a time and check the output. This is a good exercise to understand how objects are created and assigned to values, but it is for you to work out by inspecting the output versus the code that executes. Afterwards, you will understand very well what is going on.. just keep staring at it and try to understand the logic.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You must show the declaration of CharQueue in order to find the mistake. For ArrayCharQueue class to be abstract, it means that the CharQueue is abstract (has a pure method ("= 0;") that is not implemented in the ArrayCharQueue class).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>from what i seen in the examples i just assumed it stored the functions into memory

For the record, LoadLibrary puts all the DLL's code into RAM memory, but it is not part of the applications memory directly (because the DLL is shared by all applications that needs it). Then, GetProcAddress gives you the address of a function within the DLL's code in RAM. Finally, calling FreeLibrary will release the memory for the DLL's code (unless another application is still using it). So, after FreeLibrary is called that address you got before from GetProcAddress has no more meaning and points nowhere.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Holy shit! I just say the mistake... I don't know why I didn't see that earlier. In this piece of code:

HINSTANCE hInstLibrary = LoadLibrary( botPlugins[i].m_Plugins[j].c_str( ) );
                         
                        if( hInstLibrary )
                        {
                            cout << "[IRC: " << ircConfig[i].m_Nickname << "] " << botPlugins[i].m_Plugins[j] << " successfully loaded" << endl;

                            botPlugins[i]._ProcessCommands = ( ProcessCommands ) GetProcAddress( hInstLibrary, "ProcessCommands" );

                            FreeLibrary( hInstLibrary );
                        }
                        else

You cannot call FreeLibrary and expect to be able to call any functions from that DLL afterwards. You need to call FreeLibrary only at the very end, when you will not call the DLL function again. Otherwise you get an access violation if you try and call it.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It might be possible that the DLL function throws an exception, and exceptions cannot cross module boundaries (you cannot throw an exception in a DLL and catch it in the exe). That could be the source of the problem. Maybe you can try to wrap the entire function ProcessCommand with a general catch statement, as follows:

__declspec(dllexport) void ProcessCommands( const char* client, const char* location, const char* username, const char* message )
{
  try {
    cout << "DLEAGUE: " << client << " " << location << " " << username << " " << message << endl;
  } catch(...) { }; //if an exception occurs, nothing will happen or get out of the function call.
}

If it works, you still have to figure out why there is an exception (I have never heard of "cout <<" throwing an exception, but who knows.. that's all I can think of).

N.B.: those three dots "..." are intentional, it tells the compiler to catch anything (the three dots are called the ellipsis parameter.. one of the useful oddities of C++).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Since the compiler uses the type of the parameter to figure out which template to instantiate, the only information it has is the type of the parameter, it cannot "back-trace" the type from which this parameter type comes from. This is because it cannot assume that the only type T that has a Pointer typedef of the type that you gave as parameter is the type itk::Image<unsigned char, 2u>.. what if another type has the same Pointer typedef, how would the compiler choose?

To solve the problem, you could of course call Add< itk::Image<unsigned char, 2u> >(image) instead. If you want to avoid the template argument... well, I cannot think of a solution right now.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

For basic 2D drawings, there are a few options that I can think of. First, if you don't need to have much of a Graphical User Interface, Simple DirectMedia Layer (SDL) is quite easy to use and allows you to draw simple shapes (circles, lines, rectangles, text, etc.). Second, if you want to make it part of a GUI, you can use Qt, which has a QCanvas component that can draw 2D shapes and other stuff like that. I'm sure that MFC and wxWidget, two other GUI tools, also have similar components. All of the above can support a OpenGL or DirectX window, if you need 3D or better 2D drawing capabilities. There are also plenty of domain-specific visualization libraries that I'm not familiar with.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@Intrade:>>*sigh* I didn't want to bother posting this because I'll probably get flamed
Sorry if I have to light your fire here... Did I miss something? or does your implementation only do some float to string and string to float operations? I understand you take a string and cutoff to a required precision and then transform to float again. But how does that achieve anything? At best, the float after the conversion is going to be the same precision as that before, at worse, the precision is far worse after the conversion back to float. There is no gain in precision that I can think of. And most of the accuracy problem does not come from initial values, but comes from the operations themselves, and I don't see any overloaded arithmetic operators that magically are more precise than with the primitive types.

As far as overhead, interval arithmetic would be still much better than the code you posted. If you really want to achieve crazy precision levels, custom floating-point formats would be needed (like using two or three or more double variables to store the values), but that would require assembly code to reach any reasonable efficient level.

@AD: using fortran is not going to make the floating-point variables store the values with more precision than with C or C++ or even Assembly. But you are right that fortran is often cited as more suited for numerical methods, mainly because it out-performs C and C++, in terms …

Ancient Dragon commented: always have amazing answers :) +34
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you want a fixed number of iterations, use an integer value to control the iteration number and progress.

for (int i = 0; i < MaxIter; ++i)
{
  double x = dx * i;
  // numeric code
}

Many numerical methods do not require a fixed amount of iterations but might vary the step size. In this case, the original loop you posted is fine. If you want an exact terminal value of x to be Y, you can do this:

for (double x = 0; x <= Y; x += dx)
{
  // numeric code... possibly changing dx
  if( x + dx > Y) dx = Y - x - epsilon; //change dx to fix exactly to the bound (minus an epsilon of precision).
}

Two additional techniques people sometimes use when they are really really concerned with numerical errors, are rational numbers and interval arithmetics. With rational numbers (i.e. fractions of integer numbers), you can store rational numbers exactly and do simple math operations with them, but things get a little complicated when you encounter transcendental functions (sin, cos, exp, ln, etc.). So, this can avoid error accumulation for all simple operations (plus, minus, multiply, etc.) with a run-time cost of course, but it doesn't eliminate numerical errors altogether.

On the other hand, interval arithmetics allows you to track the accumulation of numerical errors (to some extent), and be able to deal with it, or to know if your results are trustworthy or not …