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

If you have no restriction as to what you are allowed to use, I highly recommend you use the class "set" (#include <set>) to store the records. In order to use it, you will need to overload the less-than operator (<) in whichever way you like to sort the elements. A simplified version of your problem would look like this:

#include <set>
#include <string>
#include <iostream>

class PhoneRecord {
  private:
    std::string last_name;
    std::string first_name;
    std::string phone_number;
  public:
    PhoneRecord(const std::string& aLastName = "",const std::string& aFirstName = "",const std::string& aPhoneNumber = "") : last_name(aLastName), first_name(aFirstName), phone_number(aPhoneNumber) { };
    ~PhoneRecord() { };
    PhoneRecord(const PhoneRecord& aObj) : last_name(aObj.last_name), first_name(aObj.first_name), phone_number(aObj.phone_number) { };

    PhoneRecord& operator=(const PhoneRecord& aObj) {
      last_name = aObj.last_name;
      first_name = aObj.first_name;
      phone_number = aObj.phone_number;
      return *this;
    };
    //this is the overloaded operators you need for having an ordered set:
    bool operator <(const PhoneRecord& aObj) const {
      if(last_name < aObj.last_name)
        return true;
      else if(last_name == aObj.last_name)
        return (first_name < aObj.first_name);
      else
        return false;
    };
    bool operator ==(const PhoneRecord& aObj) const {
      return ((last_name == aObj.last_name) && (first_name == aObj.first_name));
    };

    //to be able to print, you need the following friend operator:
    friend std::ostream& operator<<(std::ostream& out, const PhoneRecord& aObj);
};

std::ostream& operator<<(std::ostream& out, const PhoneRecord& aObj) {
  return out << "Name: " << aObj.last_name << ", " << aObj.first_name << "\t Phone Number: " << aObj.phone_number;
};

int main() {
  std::set<PhoneRecord> phone_book;
  //add a bunch of records, in random order:
  phone_book.insert(PhoneRecord("Smith","James","555-7624"));
  phone_book.insert(PhoneRecord("Doe","John","555-3424"));
  phone_book.insert(PhoneRecord("Doe","Jane","555-9803"));
  
  //print the list out:
  std::set<PhoneRecord>::iterator it = phone_book.begin(); …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

What I meant by creating a second image is that you need to make one image to store the modified pixels and keep one image intact such that you can pick the original pixels from it. So you will need to traverse both images at the same time, picking values from the original image, computing the formula and storing the result in the modified (or filtered) image.

>>I have a feeling that you have a far better grasp of the process than I.
Sure, I've done my share of image processing work. This process is at the core of almost all image processing techniques (called "convolution filtering").

I hope your exam went well!

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

It seems Clinton has got you well covered, but just to correct something.. I'm 100% sure that for this emboss function, you need to start from the upper left corner such that you don't use modified pixel values. Say you start from the last non-bordering row of the image, when you get to the second-last row, you will be using the modified row of pixels in the calculation of the second-last row. I don't think that was the intent from the formula that specifically mentions the modified pixel as a function of the two _original_ pixels.

Also, for smoothing and sharpening, you will need a second image to put the result into (you cannot perform these operations "in-place" like you can with emboss).

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

You have a whole bunch of uninitialized pointers at line 7:

int *day, *month, *hour, *min, *_hour, *_min;

Since you send those pointers by value to the function calls that you have, the only way that this program will not crash is if you don't use those parameters at all in the functions (which would be useless). You need to allocate memory somewhere and set those pointers to point to that memory. I understand that you are sending pointers to your functions such that your functions can set values of "min" "hour" etc., in that case, you should declare those as "int" (not int*) and then send them to the function as "&hour" or "&min" etc. (or better yet, use pass-by-reference instead).

jonsca commented: He'll get it eventually... +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I'm assuming you have access to the source code of the DLL, otherwise you would not be attempting to use class methods that are exported from it (there are reasons why this would be impossible). I don't know where you got your info, but the methods you tested are all very wacky and definitely wrong. I will try to put a few options that are typical:

1. Compile your DLL code directly into a .lib file (not just changing the extension nor using a third party software to convert). You will need to select as build option something like "static library". Then all you need is to include the header in your main program and specify this static library in the command line. Note that this option will make all the code that you use from this library part of the final executable (i.e. bigger exe file, but no need to distribute the DLL along with the executable).

2. If you want to export classes from the DLL, you have to use the clause "__declspec(dllexport)" between the keyword "class" and the class' name. In the header file that imports the class, you use the keyword "__declspec(dllimport)". Basically, this should be done with a #define:

//in the myDLLClass.h
#ifdef MY_DLL_MODULE
#define MY_CLASS_API __declspec(dllexport)
#else
#define MY_CLASS_API __declspec(dllimport)
#endif

class MY_CLASS_API myDLLClassName {
  //.. everything will be exported or imported
};

Simply defining MY_DLL_MODULE when compiling the dll will export the class and any other use of the header …

claudiordgz commented: Excellent insight and recommendations +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Line 78, you messed up the operation priority. It should be:

z[m] = z[m] + (2/(lambda*alpha))*diffX[m];

To match the matlab version.

BTW, if you plan to use this C++ implementation, you have some serious cleaning up to do. You have way too much temporary memory allocations and passing vectors around function calls. Consider doing pass-by-reference and merging your loops together. For example, line 59 to 70, you first traverse a vector to fill another one with the absolute values, traverse that vector to square it into another vector, and finally pass the vector (by-value) to a summation function. Why not make one loop that takes each element of the original vector, square it and sum it (no additional memory and just one single, clean loop, which would also turn your 11 lines into only 3 lines or so).

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

Roughly speaking, you could say there are three types of classes. Those whose objects are:
1- Always in a valid state (and always constructed successfully)
2- Completely useless if not in a valid state
3- Could be in an invalid state and still be useful (or recoverable)

1- A trivial example of this is a simple POD class like a 3D vector class (holding coordinates x,y,z). Then, obviously, there is no need for a function to check the validity of the object's state because in itself any state is a valid state.

2- Not all, but many resource handling classes are of this type because the object is defined by the resource it holds. If it holds no resource (because it failed to acquire it), then it is meaningless. In this case, an existing object is a valid object, and thus, there is no need to have a function to check its status. Throwing an exception upon construction is a good way to abort any piece of code that uses the resource in case of a failure to acquire it.

3- To counter the above cases, there are many resource handling classes that can either allow a partially invalid state or lose its validity. A good example of both is the std::fstream from the standard C++ library. In this case, the class handles a resource (a file) and is generally constructed to open a file and closing it upon destruction (although the open() and …

StuXYZ commented: Well thought out post +4
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

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

**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

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 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 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

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

"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

@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

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 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

@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

>> The kit I have been using is called WPILib. It is extremely easy, and open-source, but is it a good, powerful library?
WPILib is certainly very easy to use... is it powerful?.. well you don't need a sledge-hammer to kill a bug. This tool will do just fine for all your purposes. If you need to simulate your robot's operation, you will have to write another library that has all the same functions as WPILib (or at least, those that you will use). Then, you implement those functions to match the behavior of your robot (to whichever degree you like). If you need some graphics and physics, look at SDL (Simple DirectMedia Layer, for simple graphics) and ODE (Open Dynamics Engine, for simple physics). You should start by just simulating without graphics and without physics, because I know that in this type of project/competition, you run out of time quickly and there is no point in trying to simulate too much. So, focus on the abstract tasks (motion planning, finite state machine, etc.) while you don't have the hardware, and worry about hardware interface and fine-tuning of performance once you have the robot at hand.

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

The main problem is that you need to get rid of header stdlib.h it corrupts the call to getline. One simple error is that your file in the search function should be of type "ifstream" not "ofstream", calling a getline on an ofstream will likely lead to an abnormal termination (usually due to two exceptions being thrown simultaneously, or worse).

With the above changes, I ran your program and it mostly works. I would also take out the line 70 (för där finns ingen tom rad melan personer i filen).

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

As pointed out by Fbody, your copy-constructor has not a single statement that sets the mHead and mTail pointer to anything. The fact that the copied list outputs the list without the head node, is pure luck, it should just output random shit or simply crash on a segmentation fault.

So, your deep-copy is perfectly fine, it works... except that the list is copied into the head pointer "headNode" which is thrown away after the constructors body has finished executing (which is a memory leak, btw). Now, all you need to do is replace all references to "headNode" for "this->mHead". Then, you will have to add a bit of code to keep track of mTail too.

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

Being a robotics engineer, I feel a bit obligated to answer... but also very happy to do so, however, your question is too vague, thus, my answer will be as well.

>>learn the SDK in C++
What SDK? What is the platform? Is it the LEGO Mindstorm? Or a micro-processor, like gumstix? Or a micro-PC?

If it is a micro-controller, then WinAVR, AVR Studio, and Arduino are the typical examples of free software on which you can program and test your programs. But these are simple I/O emulators or embedded system emulators (not a full-blown robot simulators).

The Microsoft Robotics Developer Studio is a comprehensive tool (which I am not so familiar with since it is quite new I haven't had a chance to test it out yet). It will allow you to build simulations and test your code. However, I would imagine the learning curve would be very steep for a high-school freshman.

In my experience, developing a simple simulator for a robot is far easier than writing the code to control it. And since every robot is different, custom tools are very common. And frankly, I don't know of any generic tool, but I'm sure they exist. Mostly, people build up robotics libraries (in C or C++) over the years, and good ones rarely get out of the company or research center who paid for it! CLARAty is one example of a comprehensive …

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

There are two main reasons people ever use "char*" in C++: either they haven't learned std::string yet (meaning they are within a few weeks of having started to learn C/C++); or they are writing code that interfaces to a C library or an API written in C. If that is not your case, use std::string, it will surely be more convenient and it is usually compatible with most C-string functions too, but with stringstreams and ifstream all functionalities you might desire are already available.

The saying goes that good C++ programmers actually program in "++C" because they make use of the added features over its predecessor (C), while poor C++ programmers think they are using an improvement over C but they are actually only getting the original value. So, please try and use the best tools for your job, and, unless there are special constraints, the C++ standard libraries usually has the better tools over C libraries.

Ancient Dragon commented: good :) +34
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The point about reformatting is that you can spot mistakes in your code much more easily when the indentation is done properly. As a result, most programmers that have more than a few months of experience in coding are already fanatical about respecting format. It certainly won't magically fix any problems because the compiler ignores it, but it helps you help yourself.

As for your code (properly formatted):

int main() {

  //local constants
  const int SENTINEL = -1;
    
  //local variables
  int Base;                                //Base
  int Expo;                                //Exponent 
  int Total;                               //Total
  int Total1;                              //Calculations
    
  /**************************start main program*********************/
   
  //Get total of numbers to be inputted
   
  cout << "\n\n";
  cout << setw(50) << "--------------" << endl;
  cout << setw(50) << " Calculations " << endl;
  cout << setw(50) << "--------------" << endl;
  cout << "\n\n";
  cout << setw(55) << " Input Base (or -1 to Quit):  ";
  cin  >> Base; //notice that you set Base here, and ONLY HERE.
   
  while( Base != SENTINEL) //if you enter this loop, you will never get out because Base never changes in the loop.
  {
    if( Base <=10 && Base >=1)
    {
      cout << setw(55) << " Input Exponent:  ";
      cin  >> Expo;
    }
    else
      cout << " Base Error";
    //Isn't it strange that even with an invalid base you keep on going to the exponent?
 
    if ( Expo <=10 && Expo >=0 ) //What is the value of Expo if you entered an invalid Base?
    {
      Total1 = 1;
      for(int count = 0; count < …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The first thing you need to observe is "complexity". Intuitively, finding a random number between [0,n] shouldn't be much more complex whether n is smaller or greater than RAND_MAX. So, just a first look at your implementation reveals that something is wrong if the code is so much larger than the previous version and uses a bunch of temporary vectors too. Pay a little bit of attention to the "expected" complexity and you can know right away if your implementation is effective.

Now, let me give a few inline comments:

int nrand(int n)
{
  if(n <= 0)
    throw domain_error("Argument to nrand is out of range");

  int r;

  if(n > RAND_MAX){
    typedef vector<int> veci;
    typedef vector<veci> vecv;

    int x = 0;

    do { //put the curly braces here, don't make it too easy to get an infinite loop.
     ++x; 
    } while(n % x != 0 && n/x > RAND_MAX);
    //I think the above condition is too easy to meet! this will stop at first iteration because n % x == 0 for x==1, always.

    int y = 0, z = n/x; //please use more intuitive names then "x", "y", "n" and "z"
    vecv rec(x);
    for(int i = 0; i < x; ++i) { //use the usual bounds, the one you had was not correct anyways (it skipped the last element).
      while(y != z) { 
        rec[i].push_back(y); //do you really want to create a vector of size n, which could be 2147483647 (i.e. 8.5 GB on a 32bit computer!)
        ++y;
      } …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I found this quote to be quite nice about your topic: "An abstract function can have no functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class. A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality." -BFree, StackOverflow

@csurfer>>You cannot include a prototype of a function in a class and leave it undefined. Its a compiler error.
That's wrong. Of course you can give a prototype of a function in a class and not provide an implementation for it. The linker will only look for the implementation of the function when it is called, and it will throw an "undefined reference" if you didn't provide it. Also, sometimes the function is not reachable because it is private so its implementation is not needed at all, people use this concept all the time, with the so-called "non-copyable" idiom:

class non_copyable {
  private:
    non_copyable(const non_copyable&);
    non_copyable& operator=(const non_copyable&); 
};

In the above, both the copy-constructor and assignment operator are not reachable because they are private, but the fact that they are there tells the compiler not to generate default versions of those functions. The consequence is that the class and any of its derived classes create objects that cannot …

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

You can also use template specialization with a template... you can avoid the ordering problem of the default template argument. What I mean is this:

//create a placeholder struct for key types
template <class T>
struct key { };

//create a placeholder struct for data types
template <class T>
struct data { };

template <class T>
class list;
  //intentionally left with no generic implementation, to catch illegal uses of list.

//now specialize for key types:
template <class T>
class list< key<T> > {
  //put the implementation for the key-version of list
};

//now specialize for data types:
template <class T>
class list< data<T> > {
  //put the implementation for the data-version of list
};

//instantiate as follows:
list< data<int> > l;
list< key<short> > m;

You can also have a general implementation for key and data with a default for each, without the ordering issue:

template <class Key, class Data>
class list_details {
  //generic key and data implementation.
};

//now specialize for key types:
template <class T>
class list< key<T> > {
  template <class Data = unsigned int> //some default type like "unsigned int"
  typedef list_details< T, Data> type;
};

//now specialize for data types:
template <class T>
class list< data<T> > {
  template <class Key = short>
  typedef list_details<Key, T> type;
};

//instantiate as follows:
list< key<int> >::type a;      //list with "int" keys and default data-type "unsigned int"
list< key<int> >::type<int> b; //list with "int" keys and "int" data.
list< data<int> >::type c;     //list with "int" data …
Intrade commented: Purely awesome. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are two functions that are _crucial_ for doing random access into a file stream, that is: tellg and seekg. The first will tell you at what position the reading pointer (g) is at the moment and the second will take that pointer to a previously recorded place (obtained from tellg). This allows you to parse the file and "remember" important places, like the start of the tenth last line.

You managed to get a pretty good solution. The only problem is that if you have thousands of lines before the last ten lines, you have to read through the entire file instead of just skipping straight to the end. Here is a somewhat better solution:

#include <cstdlib>
#include <iostream>
#include <fstream>


using namespace std;

bool openFile(fstream &);
int getLines(fstream &);
int readLines(fstream &);

char fileName[20];
char * fileNameptr = fileName;
int totalLines = 0; // I am pretty sure this should start at 0.

streampos tenthLastLine; //use a stream position variable for the tenth last line.

int main(int argc, char *argv[])
{
    fstream dataFile;
    
    if(!openFile(dataFile))
    {
        cout << "Error opening file...closing" << endl;
        return 0;                   
    }
    
    getLines(dataFile);
    
    cout << "Total Lines: " << totalLines << endl;
    
    readLines(dataFile);
    
    system("PAUSE");
    
    return EXIT_SUCCESS;
}

bool openFile(fstream &file)
{    
     cout << "Please enter the file name" << endl;
     cin >> fileName;
     
     file.open(fileNameptr, ios::in);
     if(!file)
     {
         return false;           
     }    
     else
     {
         file.close();
         return true;
     }
}

int getLines(fstream &file)
{
     const int SIZE = 81;
     char input[SIZE];
     string line [SIZE];   
    
     file.open(fileNameptr, ios::in); …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, the calling convention of the DLL functions need to be declared as "stdcall;" to be easily imported to C++.

Second, in both functions ApiHook and ApiUnHook, the parameter MainApi is declared as "var Pointer" which I'm not sure how it translates to C++ (probably to void**). It appears that the assumption that "var Pointer" is equivalent to "void**" is pretty safe, so you might just leave it and try as is. If it doesn't work, you can modify both functions such that the MainApi parameter is a "^Pointer". Check carefully that you change it everywhere that MainApi is used in those functions.

Once that is done, you have two options: run-time or load-time linking.
load-time:
I'm pretty sure that Delphi can output a .lib for the DLL you compile (which is necessary for load-time linking). If you can find that option and generate the .lib file, then all you need in C++ is a simple header file with this content:

extern "C" bool __stdcall ApiHook(char* ModName, char* ApiName, void* FuncAddr, void* HookedApi, void** MainApi, int codigo);
extern "C" bool __stdcall ApiUnHook(char* ModName, char* ApiName, void* FuncAddr, void* HookedApi, void** MainApi, int codigo);

Include that header and add the .lib file to the compilation process for your C++ code. And that should be it. You will use the functions in C++ essentially the same as the code you posted in Delphi, with some "reinterpret_cast<>()" for getting around the hard-typing of C++ vs soft-typing of …

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

>>is it possible to use mmap for this.

Sure it's possible, but is it the best solution? mmap is a general one-size-fits-all solution for large data structures that are paged. It is most likely that your application can take advantage of the structure of your matrix and its usage to have a better scheme for swapping between RAM and disk.

You need to essentially look at your algorithms in terms of parallelism and see what parts of the matrix are used at a given time. For example, say your operation is a simple matrix multiplication A*B, where both A and B are very large. Then a "good" scheme might be to store A as row-major in a file and store B as column-major in another file. To do the multiplication you would do:

//say A is in fileA, B is in fileB, and C = A*B is in fileC.
for_each_row_i_of_A
  load_next_row(A,fileA);
  for_each_column_j_of_B {
    load_next_column(B,fileB);
    C[j] = 0.0;
    for(int k=0;k<N;++k)
      C[j] += A[k]*B[k];
  };
  save_row(C,fileC);
};

The above is appropriate because you have the minimum amount of loading and saving operations and all loading and saving are continuous blocks of memory (because A and C are row-major and B is column-major). You could have the same algorithm with A and C as column-major and B as row-major but the loading and saving operations would be much more expensive because you would have to load element by element instead of the entire row or column at once.

Of …

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

I think this issue is best illustrated by a simple example. Consider the following simple program:

const int four_factorial = 24;

int some_function(int* c, int* d) {
  return c[0]*d[0] + c[1]*d[1] + four_factorial;
};

int main() {
  int* a = new int[2];
  int b[2];

  int result = some_function(a,b);
  delete[] a;
  return result;
};

Ignoring a few things like housekeeping values, optimization, calling conventions or any superfluous temporaries, we can easily draw the memory pattern of the program. First, we could imagine that the program's executable file would look like this:

//code segment:
some_function:
  //compiled code for some_function
main:
  //compiled code for main
//data segment:
[four_factorial] //a memory slot holding the constant value of four_factorial

Now, once loaded and stopped just before calling some_function(), the program in RAM would look like:

//code segment:
some_function:
  //compiled code for some_function
main:
  //compiled code for main
//static data segment:
[four_factorial] //a memory slot holding the constant value of four_factorial
//memory segment (heap + stack):
//start of heap section:
[a[0]]     //value of a[0]
[a[1]]     //value of a[1]
//end of heap section
//... a whole bunch of free space (not allocated to either heap or stack)
//start of stack section
[result]   //some space for result variable
[b[0]]     //value of b[0]
[b[1]]     //value of b[1]
[a]        //value of the pointer variable a
//end of stack section

Now, if you would stop the execution within some_function, the new memory segment:

//memory segment (heap + stack):
//start of heap section:
[a[0]]     //value of a[0]
[a[1]] …
StuXYZ commented: Excellent guide. +3
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I'm sorry to say this, but there is something awfully wrong with your implementation. If you cast a pointer to CMap to a char pointer and save, in binary, sizeof(CMap) bytes, you will also save other "undesirable" things, especially the virtual table pointer (vptr) which is not going to be valid the next time you load it. If it happens to work in your save and load tests, it is just by sheer luck. Similarly, for the vector of CTiles inside the CMap object, when it is saved by just a direct pointer cast, it will probably save its internal data, like size, capacity, and a pointer to the internal array. That pointer to the internal array will be meaningless when you load it again and you will have a big memory corruption problem.

To implement a serialization library correctly, I would first recommend you look at how the boost serialization library does it. It is a very nice library and I used this approach on my own project and it is very robust.

The basic idea is that you make a class, similar in interface to iostreams in C++ std libraries, that encapsulate the format with which data is saved (this allows you to seamlessly save/load from binary or XML or any order format without change any code (just by using a different class derived of your basic stream classes). You can also use the << and >> operators for convenience. You just need to …

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

>>Also, when writing in java, especially in eclipse, you have a project folder, a source folder, a package and then the class files. Is there a similar setup I can follow with C++?

When you get into C++, you enter the land of the Free. One beautiful thing with C++ is that there are essentially no structural rules (only syntactic rules for the code) (note: this is something that really bugged me in the bits of Java I have done, to be shackled in a fixed, forced code structure).

This does not mean there are no _conventions_ used by most programmers. Below is the structure that I usually take and most code I have seen are organized similarly. This is for a program you are developing (so installs are local for testing), to release it you would just compile the src directory into a package or installer.

/trunk/: the very top level folder
/trunk/src/: the top level folder for all the source code (headers and cpp are mixed), this is the only "needed" folder
/trunk/lib/: where you dump the intermediate outputs (static and shared libaries)
/trunk/bin/: where you dump the final outputs (applications)
/trunk/include/: if a library: where you put the headers (copied from "src", i.e. "frozen" with the library releases)
/trunk/src/build/: run the "make" in another directory (out-of-source build) just to keep the src directory clean (especially important for Xplatform programming)
/trunk/src/lib1/ /trunk/src/lib2/ ..: its a good idea to organize the source files with respect to …

dohpaz42 commented: Very informative and on topic. +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>how do i make sure that the data i find by key1 is the same as the one i was pointing at and not a different data with the same key - key1?
You can't, that's the problem with multimap. If you absolutely need to have several elements associated with key1 (can't you make key1 unique somehow?). Then you would need an extra level of indirection.

>>should i just use the pointer iterator on which i have in the secondMap to erase the pointed value on the firstMap?
NO absolutely not, read my first post. DO NOT HOLD A POINTER TO AN ITERATOR OR AN ITERATOR OR A POINTER TO THE OBJECT IN secondMap!

Here is a solution to your problem (which is not trivial btw, so don't feel bad for having trouble with it, I had a bit of trouble with it myself). I implemented it as a class just for clarity. It has a bit of memory overhead, but if the object (Data) is big enough it should be amortized.

template <class SortKey, class SearchKey, class DataType>
class SortSearchList {
  private:
    typedef std::pair<SortKey,DataType*> KeyDataPair;
    typedef std::multimap<SortKey,KeyDataPair> SortMapType;
    typedef std::multimap<SortKey,KeyDataPair>::iterator SortMapIter;
    typedef std::map<SearchKey,KeyDataPair> SearchMapType;
    typedef std::map<SearchKey,KeyDataPair>::iterator SearchMapIter;

    SortMapType sortedMap;
    SearchMapType searchableMap;
  public:
    DataType& Top() {
      return *(sortedMap.begin()->second.second); //all calls are constant time complexity.
    };

    void Add(SearchKey aSearchKey, SortKey aSortKey, const DataType& aData) {
      KeyDataPair element; //constant complexity.
      element.first = aSortKey; //constant complexity.
      element.second = new DataType(aData); //"constant" complexity (heap dependent).
      searchableMap[aSearchKey] = element; //A*logN …
danalovesc commented: Great solution, couldn't come up with it myself +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

In that case, the solution I proposed at the end of my last post is not worse than that, at least in terms of complexity. The Top function is trivial since you have a map of key1 to data, so getting the first element is O(1) and fulfills you requirement. Then, the Add function has now a complexity of O(logN) but it is actually O(2logN) because you add an entry to first- and second-Map. If you have a Remove function implemented as a look-up of key1 based on key2, and then a look-up of Data based on key1, then the complexity is two calls to a O(logN) function (multimap::find()) which makes the complexity O(2logN) just like the Add function. I believe this meets the requirements. However, if you are looking to get rid of that factor of 2, you are in trouble.

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

I have to say that I disapprove greatly of this code you posted. I cannot sanction the idea of getting a pointer to a pair that is used in a map or multimap object. This is because you don't know, and I don't know, how multimap implements it list of pairs (is it a linked-list or an array?). The standard prescribes that the iterators given by multimap are bidirectional iterators (not random-access iterators) which could indicate that the implementation is a double linked-list (however not guaranteed). There is a good reason why this is not strictly defined: freedom of choice = optimization possibilities. So, I don't know which is used and, as they say, ignorance is bliss (which holds very well with the idea of abstraction in C++).

The problem with this, is that there is no guarantee that the pointer to a pair in the map will remain the valid or still pointing to the same pair after you add or remove any element from the map (resorting might shift all the elements). I highly recommend you rethink your implementation to avoid taking a pointer to a pair inside the map.

For the compiler errors you are getting, first, a pointer to a pair and a map iterator is not the same, so the assignment of itr to it->second is not valid and can never be made valid by any tricks. Imagine you have a linked-list implementation, then the map will store each pair within a node …

danalovesc commented: Great post, helped me a lot +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This line:

foo * var[5];

creates five pointers to a foo object, but that does not create five foo objects. var will hold 5 pointers to no-where or anywhere, which is the same.

To initialize five foo objects for those pointers to point to, you need to do this:

foo* var[5];
  for(int i=0;i<5;++i)
    var[i] = new foo;

Then you need to delete them with:

for(int i=0;i<5;++i)
    delete var[i];
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Line 15: the bound on the loop is wrong.. simple typo, you wrote i where it should be j:

for (j = 0; i < EVEN; j++)
//should be:
		for (j = 0; j < EVEN; j++)
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

On a technical side, you have a problem with pointers / references / objects. A pointer is an address to an object of a class. An object is allocated for and created with new and destroyed and deallocated with delete via a pointer to that object (not a dereferenced pointer). A reference is an alias for the object and thus should not and needs not be dereferenced to access the object.

On a more fundamental side, you need to look at issues of object-ownership and deep- vs. shallow-copies. In your example, you are mixing the two. Generally, if an object owns another object (via a pointer to it), it is responsible for deleting it and thus it cannot give that pointer-to-object away to another object without either transferring the ownership or performing a deep-copy (meaning allocating a new object to which the previous one is copied). A very good way to solve those problems is to use smart pointers (unique_ptr, shared_ptr, weak_ptr).

So, the options are (with implementation):
1) An object of class SomeClass owns the object pointed to by myMember:

class SomeClass {
  public:
    SomeClass(int size) : myMember(new OtherClass(size)) { };
    ~SomeClass();
    SomeClass(const SomeClass & other);
    SomeClass & operator=(const SomeClass & other);
  private:
    OtherClass * myMember;
};
/* this is bad because it makes both objects "this" and "other" share ownership (the first to be deleted will corrupt the other).
SomeClass::SomeClass(const SomeClass & other){
  myMember = other.myMember;
  myMember = new OtherClass(*(other.myMember));
}*/

//instead, perform a …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think the best way to look at this problem is by dividing the tasks properly. I think your Othello class seems to be ill-defined, as you said it does "almost everything" that's a bad sign that you can't even clearly say what it does or what it is responsible for. In this type of simple game logic, things are usually separated as (or at least from my experience):
Data handling:
1) Global Housekeeping: That means keeping track of the environment and the list of objects in it (like the Othello board with the list of Fields)
2) Local Housekeeping: That means keeping record of the change of state of individual objects (like black or white for a Field)
3) Player Status: That means keeping track of scores, name, etc.
Functionality:
4) Game Logic: Handles all the rules by which objects interact (deciding what moves are legal, automatically reversing fields after a valid move, establishing the winning condition, etc.).
5) Player Controller: Handles how moves by a player is generated and provided to the game logic (is it a command-line prompt to the user? is it a GUI button? is it obtained from a network connection? is it generated by an artificial intelligence (bot)? etc.).
6) Display: Handles how the game is displayed (in 3D gaming world, that is called the Renderer) (is it a piece of ASCII art in a command-line? is it a windows form? is it OpenGL or DirectX? …

iamthwee commented: Nice logic and tightly written up as well, props to you. +13
StuXYZ commented: Great post +3
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Now, the problem is the difference between an object and a pointer to an object. Think of a class as any other type (like int or float or double), if you declare a variable with * it's a pointer to an object, if you declare with & it's a reference to an object, if you declare with neither then it is the object and cannot be set to NULL or any other "invalid" or "empty" value and has to be initialized by one of its constructors.

There are many little things to rectify, see comments in the code (and please post in proper code tags in the future):

#ifndef ACTOR_H_
#define ACTOR_H_

#include "Point3D.h"
#include "Date.h"
#include <iostream>

//using namespace std; //Don't import namespaces in header files!

class Actor {
  public:
    Actor();
    //HERE: you should inline trivial functions -> more efficient and less code bloating in the cpp file.
    std::string getName() const { return name; };
    double getMaxSpeed() const { return maxSpeed; };
    int getWeight() const { return weight; };
    int getHeight() const { return height; };
    double getTendency() const { return tendency; };
    //HERE Date may be a complicated class, better output a const reference instead (same for Point3D).
    const Date& getInception() const { return dateInception; };
    const Date& getDeath() const { return dateDeath };
    const Point3D& getLocation() const { return location; };

    bool validityWeight(int testWeight);
    bool validityHeight(int testHeight);
    bool validityTendency(int testTendency);
    std::string getCharacteristics();

private:
    std::string name;
    double maxSpeed;
    double tendency;
    int height;
    int weight;
    Date dateInception;
    Date …
mrnutty commented: I don't know how you can answer to such a bad post, but hats off to ya +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Again, polymorphism comes to the rescue. It is extremely typical, in fact I don't remember ever seeing any other solution to this, to use a "renderable" interface class and make all your objects that need to be rendered as derived from that interface:

//interface for all renderable objects
class Renderable {
  public:
    virtual void render() = 0; //pure virtual render method.
};

//say you have a class Square, which is derived from another class Polygon, derive it also from interface class Renderable
class Square : public Polygon, public Renderable {
  ...
  public 
    ...
    void render() { ..put rendering code here.. };
}; 

//Say you have a Canvas class that holds all things that are rendered to the screen or window:
class Canvas {
  private:
    std::vector<Renderable*> Objects; //hold the list of renderable objects.
  public:
    void render() { //Canvas has its own render function, of course.
      ... initialize screen (like clear buffer, load camera, etc.) ...
      for(int i=0;i<Objects.size();++i)
        if(Objects[i])
          Objects[i]->render(); //render all the objects.
      ... finish off ...
    };
};

I have programmed several game engines and other visualization stuff, and that's basically the way to go, most of the time (at least in simple cases).

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

In this case, there are several options available to you. Here are two that I would recommend (btw, these are examples you can compile and run):

1) Polymorphism: This is a basic object-oriented implementation for this problem using an interface class for all class that could implement a response for your mouse release event. It goes as follows:

#include <cstdio>

//define an interface class for all the responder classes 
class ReleaseResponder {
  public:
    virtual void OnRelease() = 0; //with a pure virtual response function (callback).
};

//hold a pointer to that interface class in the Button class:
class Button {
  private:
    ReleaseResponder* responder;
  public:
    Button() : responder(NULL) { };
    void setActionOnReleased(ReleaseResponder* aResponder ) { 
      responder = aResponder;
    };
    void mouseReleased() {
      printf("mouse released");
      if(responder)
        responder->OnRelease();
    };
};

//Make whatever class you want to use as responder implement the responder interface:
class AClass : public ReleaseResponder {
  public:
    //....
    void OnRelease() {
      printf("responding...");
    };
};

//then you set it up as:
int main() {
  AClass* myResponder = new AClass();
  Button* myButton = new Button();
  myButton->setActionOnReleased(myResponder);
  //test it:
  myButton->mouseReleased();
  return 0;
};

2) Generic Programming: Now this is more advanced and is a basic form of template meta-programming. You will probably not choose this because of the additional complexity, but it is far more flexible as the example demonstrates. The idea is to use a template policy class to implement the mouse release response (as a callable policy):

#include <cstdio>

//define a default policy class for all the responder policies …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think it's a bit of a silly question. It is known that men and women have different and often complementary abilities (or at least inclinations for certain abilities). Since programming requires such a wide array of skills, I think you would probably find as good programmers in both genders, but maybe their particular skills might be camped on different aspects of programming (that could be quite an interesting study to do!). But I think there is hardly any way you can say whether men or women are definitely better. In fact, most psychologist would tell you that women often do better in academics mostly because the academic system (the form of courses and exams) are better suited for the female-psyche (especially for younger children and teenagers). Also, maybe programming is a bit more popular with men because of its nature (women tend to prefer so-called empathic professions like medicine, nursing, psychology, etc. because they prefer to work with people while men prefer to work with "things" like building or fixing stuff).

Final note, you know that this forum is under the reign of our all-mighty goddess of coding: Narue. I would anticipate a strong reply from her on this thread.

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

Hi experts!
I have the following code which I use for dynamically creating objects in one module (executable or shared object (.so or .dll)) and be able to delete it from any other module while enforcing the call to the delete operator in the original module where the object was created (such that the same Heap is used for sure). This is essential for being able to easily use the shared_ptr across the modules while not having to care about in what module the object ends up being deleted by the depletion of the shared_ptr reference count.

However, I am not entirely happy with the semantics of it and also with the fact that it would be even nicer if the old-fashion delete operator could be used directly (instead of a "scoped_deleter" callable function object). I tried other alternatives, such as the one proposed here in the "final implementation". But all my trials at overloading the delete operator for that purpose has resulted in segmentation faults, pure virtual method call crashes, or worse.

So far, I have not really used my library (for which these two classes and a few others form the basis of) in different modules, only in different static libraries. So I would like your opinion on this before it gets too "carved in stone". I know there are people here with a bigger bag-a-tricks than me, and I look forward to hear some good suggestions. Thanks in advance.

/**
 *\file …
sergent commented: You are too smart for anyone to help you lol +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think the proper logic for the if-statements is this:

if(isalpha(textstring[i]))   //if it is a letter (not a number or other crap)
{
  letters_total++;           //increment letter count.
  if(isupper(textstring[i])) //if upper-case,
  {
    textstring[i]=tolower(textstring[i]); //then make it lower case.
  }
  histogram_abs[(textstring[i] - 'a')]++; //at this point, only a lower-case letter could be in textstring[i].
}

As it was before, only the capital E would be counted and only capital I (which is obviously more common in English).

John Sand commented: Great advice on C++ programming. +1