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'm assuming you mean a graphical game (like 2D or 3D) because otherwise there is really nothing else you need besides a compiler and reasonable knowledge of C++.

For either 2D or 3D, I find that OpenGL is a good place to start and the NeHe tutorials are really easy to follow and get you to do nice things quickly. For 2D only, just simple SDL can also be quite easy (don't know any particular tutorial to recommend).

For making a GUI-based game (i.e. traditional windows-like applications), then it is just a matter of picking the right GUI tool and library. Generally people seem to like Qt or wxWidget, because they are easy, free and cross-platform (windows, linux, mac, and many mobile phone or microOS platforms).

Other than that, basically, game programming requires good knowledge of object-oriented programming in C++. In other words, I would not recommend you start programming computer games without being quite comfortable with the object-oriented approach, because it will be very difficult and time-consuming if you have more of a C-style approach to doing C++ as opposed to making good use of polymorphism and abstraction.

Other than that, there are a few helper libraries that you can get open-source and will surely save you some time along the way, just browse for what you need on sourceforge and you should find it. Of course, learn to use the C++ Standard Template Library (STL) as much as possible, it is the …

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

Hey y'all,
I have been working on a tensor library (Nth-order multi-dimensional arrays) and I've been having trouble coming up with a good scheme for a multi-dimensional iterator template. Basically, I have a class template "tensor_container" which stores all the values of the N-order array (as a std::vector of one dimension) and the size of each dimension. The values themselves are thus serialized as a 1D vector with the lowest level being continuous (e.g. a second order tensor would correspond to a column-major matrix).

Now, I pretty much managed to get the indexing to work just fine with a few template specializations, such that now, an element of tensor "a" of order 4 can be accessed as "a[2][5][1][4]". This is accomplished by this simple code:

template <class Iterator,int Level> //here, Iterator is an iterator for the 1D array or vector and Level is the level of the index.
class tensor_indexer : public boost::noncopyable {
  private:
    Iterator start; //stores the start iterator for this level, on flat data storage.
    int *dim;       //stores the pointer to the dimension of the current level
    int accum;      //stores the accumulated stride for indexing.
    tensor_indexer(Iterator aStart, int* aDim, int aAccum) : start(aStart), dim(aDim), accum(aAccum) { };
  public:
    //this operator[] just returns a tensor_indexer for the next level.
    tensor_indexer<Iterator,Level-1> operator[](int i) {
      accum *= dim[0];
      return tensor_indexer<Iterator,Level-1>(start+i*accum,dim+1,accum);
    };
    friend class tensor_container<typename std::iterator_traits<Iterator>::value_type, Level+1>;
    friend class tensor_indexer<Iterator,Level+1>;
};

template <class Iterator> //template specialization for level 1 (terminal level)
class tensor_indexer<Iterator,1> : public boost::noncopyable {
  private: …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

very simple:

int last_time_ms = some_time_function();
for(int year=0;year<MAX_YEAR;++year) {
  //perform your task..
  int current_time_ms = some_time_function();
  sleep(2000 - (current_time_ms - last_time_ms));
  last_time_ms = some_time_function();
};

that's it. If you are looking for a good time function, I would suggest Boost Date-Time library, which would turn into:

#include <boost/thread.hpp>
#include <boost/posix_time.hpp>
//...
boost::posix_time::ptime last_time_ms = boost::posix_time::microsecond_clock();
for(int year=0;year<MAX_YEAR;++year) {
  //perform your task..
  boost::posix_time::ptime current_time_ms = boost::posix_time::microsecond_clock();
  boost::this_thread::sleep(boost::posix_time::seconds(2) - (current_time_ms - last_time_ms));
  last_time_ms = boost::posix_time::microsecond_clock();
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yeah, definitely, this is what was expected to happen. The reason why you get so much iterations is because of virtual memory. You said you had 467K available... was that 467M, because if it is only 467K out of 1G, you should think of fixing something because I imagine your computer will be extremely slow at running anything (you essentially have no more RAM to execute anything but the OS... classic windows problem!). Anyhow, on winXP, I believe the default size of virtual memory is 2GB, which would exactly explain the amount of iterations and the slow response of the computer. The OS essentially just loaded the program on the hard-drive, expecting way more memory demand that it could provide on the RAM, leading to slow execution, freezing of the rest of the programs, and ultimately running out of the 2GB of virtual memory.

Now, there is nothing "dangerous" about running a program that runs out of memory. The OS loads programs in a sort-of controlled environment, it cannot affect the other programs by other means than just making the whole computer extremely slow while the program is running. Now, when the uncaught exception "bad_alloc" is thrown, the OS kills the process and frees all memory associated to it, and you are back to normal.

The reason why some ill-intentioned people can use memory exhaustion as an attack is basically because it is an easy way to make a computer / system / server unresponsive to anything else …

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

Consider this simple example:

double twice(double d) {
  return 2.0*d;
};

int main() {
  double result = twice(2.0);
  std::cout << "result is: " << result << std::endl;
  return 0;
};

This would, most probably, with no optimization and no inlining, to something like this in pseudo-assembly code (I'm just a novice in real asm and can't write this):

twice:
  //here it does some preamble like pushing the stack frame and instruction register
  mov fr(0), -8(%ebp)   //fetches the parameter from the stack
  mul fr(0), $2.0       //multiplies fr(0) with 2 and stores it in fr(0)
  mov -8(%esp), fr(0)   //puts the result on the stack for return value
  mov %edx, %esp        //copies the stack frame address on edx register (result)
  sub %edx, $8          //decrement result pointer to point to the actual pointer
  //unwinds the stack frame
main:
  //does some application starting stuff
  sub %esp, $16          //allocates 16 bytes for both the parameter and result
  mov -8(%esp), $2.0     //writes the value 2.0 in the smallest address stack position (in the parameter spot directly)
  call twice             //calls the function twice
  mov -16(%esp), (%edx)  //copies the value pointed to by edx (result) to stack position -16 from esp
  //call the std::cout printing stuff using the result value in stack position -8 from esp.
  //unwinds the stack before exiting.

The lesson to take from the above, is that if the parameter that is passed to the function is already stored in the stack frame of the caller, the compiler will try to initially place it …

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

make sure that the method "printSummary()" is also defined as const, like this:

class MutantType {
  //stuff here...
  public:
    void printSummary() const { //notice the const after the function prototype.
      //..print stuff but cannot change any data member value.
    };
};

otherwise, the compiler will throw an error saying you are calling non-const method on a const object.

For the rest, your use of constness (const reference to list and const iterator) is correct.

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

In my opinion, there are things that are important, others not so much. What I can think of, off the bat:

Important stuff includes:
- have clear names for classes and variables (identifiers), even if it makes them longer (IDE code-completion solves the extra typing issue, and it doesn't work if the variable or class name is not obvious and clear, and thus, "guessable").
- use all upper-case for the few MACROs that you might need, and include some prefix too, like MY_LIBRARY_SOME_MACRO instead of just SOME_MACRO.
- use namespaces a lot, because it frees the vocabulary and allows you to safely use good names for classes and variables without name clash dangers.
- provide full doxygen-style comments of each function, each class, each type, each member, each method, each every-freaken-thing that you find in a header file. And use the tags like \param, \return, \note, \test, \todo, \throw, \author, \date, etc.

Not so important, but still desirable IMO:
- be consistent with the capitals and other wording for everything that is public, i.e. class names, public and protected class methods and members, namespaces, global/namespaced functions, etc. I generally try to mimic the STL and the Boost conventions, which are essentially using all lower-case and _-separated words for class, namespace and type names, and leading lower-case, camel-back and no prefix (like m_ or p_) for data members and methods.
- put only trivial implementations in the header files, a few lines at …

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

Your question(s) is very broad. But I think that basically you are on the right path (at least in my opinion). Learning to be a skilled programmer does involve a lot of bits and pieces that you get acquainted to along the way. You said you already learned to work with a few different things like MFC and others. This is essentially how it goes. You start with a problem, say doing simple 2D/3D graphics game. Then you go question by question. If the first question is "how will I render/display the graphics?", then obviously by a little web browsing you will eventually find a few ways to do that (e.g. Direct3D, OpenGL, OpenInventor, SDL, etc.) you pick the one you like or think is the most powerful or standard or useful, learn it like you learned MFC, by making simple applications and incrementing the complexity. Then you move on to the next open question. After a while, you will be "specialized" in certain libraries and types of programs. But moving towards the "generalized" skill of being able to work with any library, that is a combination of skill with the programming mechanics (syntax, programming idioms, OOP, subversioning, cross-platform development, etc.) and with using libraries which means to be able to download a library, solve the dependencies (linking and including), and understanding the library's documentations to learn to use it. These are things that take time to develop and there is no shortcut. Reading books that are comprehensive about the …

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

I think you would have better luck in a forum dedicated to Boost and/or Regex questions. One thing I can suggest is that the Boost Regex has to be linked to its binaries too (boost_regex.lib or libboost_regex.so/a), so make sure that is set up correctly (if not you should get loads of "unresolved external reference" errors). Also, we have seen here many people with weird problems with Dev-C++, so consider either giving it another go with VS or installing Code Blocks instead.

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

>>however IF AN ASSIGNMENT OPERATOR is not defined and assignment(other than in declaration) is performed then if i have understood your's and mike_2000_17's post, the copy constructor is called. so the following code fragment will result in memory leak

Just to clarify: when the assignment operator is called, the copy-constructor is not called at all, but the compiler will produce a default assignment operator that essentially just assigns each data member of the Right Hand Side (LHS) to the Left Hand Side (RHS), i.e., a shallow-copy. So the code you posted there does not only lead to a memory leak, but makes both objects "a1" and "a2" share the same pointer (so, at delete time of both a1 and a2, the one that deletes first will be fine, but the second one to get deleted will "crash" (well it might not actually crash but there is an unacceptable chance that it will, especially if there are a lot of other operations between the two delete calls).

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

Ok.. here's the deal.
When you hold a pointer within an object you need to clarify "who" owns the pointed-to memory. If the object owns the pointed-to memory, then you have to perform a deep-copy of the object if you assign it to another one and in this case there is no other way but to define an assignment operator for that class. Look up the topic of shallow-copies vs. deep-copies.

Yes, deleting a dangling pointer is a VERY BAD IDEA. And by the way, in the simple example you posted, you do delete a dangling pointer:

class A
{
    int *p;
    //other members
    public:
    A(&A)
    ~A();
    A();
    A(int a);
    //other functions
}

A::A()
{
    p = NULL;
    //other initializations
}
A::A(int a)
{
    if(p!=NULL) delete p;   //at this line, the value of p is not initialized at all
                            // because a constructor is always called on a "fresh"
                            // object and only called once. So this line will delete
                            // an uninitialized pointer (BOOM.. CRASH!!!)
                            // note: some compiler will issue a warning here.
    p = new int;
    *p = a;
}

Now, I need to explain the sequence of event when you assign a value (3) to the object of class A. Since the object "a1" has been constructed already, its constructor is not called again for sure. But a constructor is called to create a temporary object of class A that is constructed with A::A(3). This is because you cannot assign an int to …

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

First part: for the pow() function issue. I would suggest you just avoid it altogether by a simple multiplying accumulator:

int Poly::evaluate(int x)
{
  int total = 0;
  int x_pow_term = 1;
  for(int i = 0; i <= degree; i++){
    total += coefs[i]*x_pow_term; //coefs[] array is the array in which the coef's are stored
    x_pow_term *= x; //just multiply the previous term by x, so: x^i = x^(i-1) * x (with x^0 == 1)
  };
  return total;
};

Second part: all that I can see that could be wrong is if you didn't initialize your array temp.coefs to zero. Try adding this to see if the output is better:

Poly::Poly operator*(const Poly& p)
{
  Poly temp;
  temp.degree = degree + p.degree; //this resizes coefs right?
  if(temp.degree > 99)
    cout << "cannot evaluate";
  for(int i = 0; i < temp.degree; ++i)
    temp.coefs[i] = 0; //set all the sum values to their initial zero.
  for(int i = 0; i < degree; i++){
    for(int j =0; j < p.degree; j++){
      temp.coefs[i+j] += coefs[i]*p.coefs[j];
    }
  }
  return temp;
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

you only need to call srand(time(0)) once during the application's execution. So the function you have is not dependent on time and you can generate your random numbers as fast as you like (just take the srand() call out of your function and call it once at the start of the application only).

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

You are missing one star at line 4 of the second code snippet:

temp2=(char***)malloc (FIRST_DIMENSION * sizeof(char **));

For the rest, it is the correct way to do it.

BTW sizeof(char) is always equal to 1, by definition from the standard.

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

From the link you gave, first, these are recursion formulas, meaning that they are calculated as the data comes in, so all those calculations should be within that value-entering loop you have (or you can loop through the data in another function and apply the formulas). Since there aren't that many symbols to understand I can give you a quick definition of them:
x_n : is the new element that was just given by the user.
x(bar)_n-1 : is the average or mean computed up to and including the previous element (x_n-1)
x(bar)_n : is the average or mean that includes the new element x_n
n : is the number of elements inputted so far (cnt), including the new element x_n
s2_n : is the sample variance (s_n being the mean deviation) that includes the new element x_n

That's about it. The sigma one is for a population instead of sample, that's just a weird statistical technicality. You will notice that the formula for the sample variance will be undefined for the first element (n-1 == 0), but that's alright because the variance of a set containing only one element has to be zero (the element does not deviate from itself!). So both the variance and mean deviation start with a value of zero, and you start counting them with those formulas from the second element and on.

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

You disassemble the code, look for the label "checkPassword", look for a comparison operation on the parameter "password", find the memory location of the other compared element "myPassword" and extract the value. Or, find token "checkPassword", replace the comparison operator by a comparison between password and password (always true), and you get that all passwords are valid (that is essentially how most "cracked" software are done, just by replacing the part that authenticates your CD or license by dummy operations that always yield a positive verification).

This is not reverse engineering, just requires very basic knowledge of assembly code and a decent disassembly tool.

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

Here is the solution (I guess it has to do with priority of operations, I never had that problem before, but again, I rarely use pointers to member functions):

(pointerToBase_->*pointerToComputeFooFunc_)(aValue); //notice additional parentheses.
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Sounds like plugin system?
If so, then make plugin loader/Manager.
All plugins will share interface file, let say plugins.h where variable holding the password is defined. then in all methods of the DLL, check password first and if doesn't match, return some garbage. Else do a process!

void checkPassword(std::string password){
    if(password==myPassword){
            return true;
   }else{
       return false;
   }
}

The problem with that is that even a guy like me who is not by any means a professional hacker (never done any hacking at all) could break this protection in a matter of minutes.

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

The compiler has to know that a function called "overDraft" exists before it gets to a line that calls that function. There are two options:

1) you can declare that the function exists by putting a "prototype" of the function before "withdraw". The prototype for overDraft has to exactly match the function definition (but parameter names can be omitted) as follows:

bool overDraft(int pin); //prototype of overDraft, to put before withdraw

2) Just invert the order of the two functions:

bool overDraft(int pin){
    if (pin ==123)
        return true;
    if(pin==456)
        return false;
    if(pin==789)
        return true;
}

bool withdraw(double amt, int pin){
    if (amt <= bal)
        return true;
    if(amt >= bal)
        return overDraft(pin);
}

Enjoy!

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

I'm not a security expert either, but here is a thought to add to the options already given.

Write a little program that generates a module definition file (.def) for your dll with all the aliases (symbols) of the functions encrypted, so a user app won't be able to load the functions without having some sort of table to translate from meaningful names to their encrypted aliases. Then write another application that can verify the password and decrypt the aliases. This will require you to use dynamic loading (LoadLibrary, GetProcAddress, and so on), but that's usually quite alright. A good hacker would probably break this in a few hours at most, but it's good enough for your typical average joe or lazy programmer.

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

yeah line 109 should be:

displayGame(trivia,count);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The prototype of displayGame needs to match its definition _exactly_. So you need this prototype instead (at the beginning):

void displayGame(Game[], int);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I added using namespace std in Product.h file.

There is a good reason why I didn't suggest that "simpler" solution in my previous post. That is because it is considered bad practice to import a namespace in a header file (which is what "using namespace std;" does). It is considered bad practice because one untold rule when writing header files is that the "trail" of it should be minimal. In other words, besides the stuff that is actually declared in the header file and the other essential dependencies, nothing more should get imported when you include that header file somewhere else (minimizes code bloat, decrease compilation time and avoid possible name-clashes). But for your simple program that won't make a difference, but it is a good thing to get used to.

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

Well, just uncomment the line 153 you have and it should work. Doesn't it? I would say that you need to implement a deep copy-constructor for class student_Univ, but, since your management of memory, pointers, and ownership is essentially non-existent in your code (which is very bad, especially when working with linked-lists), I guess you have to stick with the shallow copy-constructor that the compiler provides.

Two remarks:
1) You have a ton of memory leaks (not dangerous ones, but still). You should google for the topic of memory leaks and revise your code (essentially you need to add clean-up code for all that dynamic memory you are allocating). You need to better understand pointers, dynamic memory, and ownership issues.
2) Hint: classes student_Univ and doctor_Univ are not needed. This is a common mistake when making a simple linked-list. Except for a few special purposes, decentralized (recursive) algorithms, as part of classes student or Doctor, can pretty much do everything you need the linked-list for, and thus, no "managing" or centralized classes or algorithms are needed.

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

Instructions to get the above to compile:

1) add #include <string> at the start of the Product.h file.
2) replace each use of type string with std::string in the Product.h file.
3) add "using namespace std;" just after the includes in the Product.cpp file
4) as said by firstPerson, include the Product.h in the main.cpp (TestProduct.cpp)
5) compile both cpp files together, say you have a gcc (g++), the command-line is (no .exe if in Linux):
g++ TestProduct.cpp Product.cpp -o TestProduct.exe
If it is not gcc or another command-line compiler, then look in the project menus of your IDE for "add source file to project/build" (or something of the like).

That should do it.

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

@mike:
what happens if all the keys are identical? we could run on the entire map? and this is O(N) complexity.. any solution for that?

Sorry for the late reply. In order to avoid a O(N) on the search for the right object associated to a key that is the same for N other objects. You would have to sort with respect to object pointer too. For example, this is a composite key that could be added:

template<class SortKey,class DataType>
struct CompositeKey {
  SortKey key;
  DataType* data;
  CompositeKey(SortKey aKey, DataType* pObj) : key(aKey), data(pObj) { }; //not needed in C++0x
  bool operator <(const CompositeKey<SortKey,DataType>& RHS) const {
    if( key < RHS.key)
      return true;
    else if(key > RHS.key)
      return false;
    else //this is the case that key == RHS.key
      return (data < RHS.data); //apply second level of sorting.
  };
};

This makes all the keys unique (map instead of multimap) but there could be quite a bit of memory and processing overhead by introducing a larger and more complex key type. So in this case, it is a matter of finding the optimum for your case (do you expect that normally there are only a few elements that have the same key or is it more usual to have a lot of elements and only a few different keys). Computer scientist like to put everything in O() form because it is nice and easy, but in real-life there are often situations where something with a worst O() is actually …

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

I don't see anything wrong with your implementation except for this trivial piece missing in the main() to see the result:

vector<string> result = split(expression);

  cout << expression << " split into individual entities yields: ";
  for(vector<string>::iterator it = result.begin(); it != result.end(); ++it)
    cout << "'" << (*it) << "', ";
  cout << endl;

When I compile and run it, I get this output:

Enter an expression: 43+4-5-(4*5)
43+4-5-(4*5) split into individual entities yields: '43', '+', '4', '-', '5', '-', '(', '4', '*', '5', ')',
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You store the values if you need them later, you don't if you don't need them later. For the sum itself, you will only need a temporary variable to save the input but not a permanent array. To store all of them in a "single variable", that variable will have to be an array (or std::vector). This page on vectors has what you need.

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

Ok, so from what I understand, you need basically the freedom of the generic programming option without using anything "too complicated for the users of your library". In other words, you want to avoid templates, policy classes, even multiple inheritance... essentially anything outside the capabilities of a very novice programmer (who probably should not touch your library anyways, or any other libraries for that matter).

To solve the problem, there is little you can do to mimic generic programming at run-time (not at compile time with templates) without adding overhead (time + memory), but I guess that doesn't matter to you. Building on your code, the simplest solution is abstraction, which can be realized in two different ways here:

class BaseClass; //forward-declaration.

class FooClass
{
  public:
    typedef void ( *pointerToDoubleTakingFunction ) ( double& );
    typedef void ( BaseClass::*pointerToComputeFoo ) ( double& ); //note BaseClass here.
  private:
    pointerToDoubleTakingFunction pointerToDoubleTakingFunction_;
    pointerToComputeFoo pointerToComputeFoo_;
    BaseClass* pointerToBase_; //note: you need a pointer to BaseClass in order to call pointerToComputeFoo_
  public:
    FooClass() : pointerToDoubleTakingFunction_(NULL),
                 pointerToComputeFoo_(NULL), pointerToBase_(NULL) {};

    virtual ~FooClass() {};

    void setDoubleTakingFunction( pointerToDoubleTakingFunction
                                                  pDoubleTakingFunction )
    {
        pointerToDoubleTakingFunction_ = pDoubleTakingFunction;
        pointerToComputeFoo_ = NULL;
        pointerToBase_ = NULL; //note the two options are mutually exclusive.
    };

    void setDoubleTakingFunction( pointerToComputeFoo
                                                  pComputeFoo, BaseClass* pBase )
    {
        pointerToComputeFoo_ = pComputeFoo;
        pointerToBase_ = pBase;
        pointerToDoubleTakingFunction_ = NULL; //again, mutual exclusion.
    };

    void setDouble( double doubleValue )
    {
        doubleValue_ = doubleValue;
    }

    //OPTION 1: as before
    virtual void run_OPTION1() = 0;

    //OPTION 2: implement a public run function that calls a protected …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is an issue that comes up once in a while on this forum and others.

The first option that you can consider is the one that you are already trying to implement and with the link in evstevemd's post, it shouldn't be a problem to fix the syntax.

However, I personally rarely see the use of pointers to member functions because it can more easily be implemented with an interface class and multiple inheritance, without any more restriction than those already imposed by the pointer-to-method solution. Here is an example of that that I had previously posted sometime ago (for a "button release" callback function):

#include <iostream>
//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() {
      std::cout << "mouse released" << std::endl;
      if(responder)
        responder->OnRelease();
    };
};

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

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

The third option that is good if you really don't want any …

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 is a classic problem that comes up almost every day on this forum. The reason for this problem is that when you do a getline, it will get the string up to the first newline (enter stroke) and will delete that newline from the input buffer. But, when you get a numeric variable (int or char or double) it will get the first valid value (ignoring newlines and spaces before) and it will leave the spaces or newlines that are after the numeric value on the input buffer. So after you got a numeric value input, there will be a dangling newline or space character on the input buffer. This will not affect subsequent numeric inputs because they will be ignored and skipped, but it will affect the next string inputs (getline) because the getline will see the newline character on the input buffer and output the string before it (usually empty, or just spaces). To solve the problem, you should add, right after any numeric value input, the line:

cin.ignore(); //this will flush out any dangling newlines on the input buffer.

That will solve the problem for sure.

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

Well, I will do a little leap of faith and trust that you actually put some effort into it. Here is a very simple example that contains all that you need to do those two problems:

#include <iostream>

using namespace std;

int main() {
  double width = 0;
  double length = 0;
  cout << "Enter the width of the rectangle:" << endl;
  cin >> width; //this takes the user input for the width
  cout << "Enter the length of the rectangle:" << endl;
  cin >> length; //this takes the user input for the length

  double area = width * length;
  cout << "The area of the rectangle is "
       << setprecision(2) //this sets two decimal points display
       << area; // this prints the area that was calculated

  return 0;
};
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

Ok... the problem here is that you are confusing the idea of a class and an object. A class is a type that you define. In a class, you declare what data an object of that class holds and what functions (methods) can be used on that data. The object is an instance of that class in memory (with the data declared in the class). You should read on the subject to get a better grasp of it because it is central to object-oriented programming.

The problem that you are having in this example code is that when you create an object, called individualBirth, with a default constructor (that is implicitly provided by the compiler), the data in it is empty (or, in your case, the debug compiler you have seems to fill that memory with 123123123.. values to help you notice that the memory is not initialize by your code). Since none of the subsequent calls to validate the day and month actually set the data members of object "individualBirth", it never gets initialized at all.

When you call "Date(setDay,setMonth,setYear);", what happens is that a new object of class Date with no name is created with the initial values given, but it dies out right after the semi-colon of the same line (since there is no identifier for it). So that line has no effect at all (and if your compiler is clever, it should warn you about that... warnings are very important!).

Now, here is …

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

What you have here is what is called "circular referencing" meaning that first.cpp needs what is in second.cpp to be defined and second.cpp needs what is in first.cpp to be defined (so what comes first, the egg or the chicken?).

Luckily, C++ has a mechanism built-in for that exact purpose, i.e. breaking circular referencing. This mechanism is called "forward-declarations". This is done by simply having an empty declaration of a class that is fully declared later but that can be used in the mean time to declare other stuff (only pointers and references to the forward-declared type).

In your case, the solution is very simple:

//first.cpp
#ifndef FIRST_CPP
#define FIRST_CPP

//forward-declaration of myClass.
class myClass;

namespace myNS
{
  myClass* myClassPtr; //now a pointer to myClass is legal even without including second.cpp, as long as it will eventually appear in the compilation unit.
  int justAnyNumber;
}
#endif

//NOTE HERE: first.cpp will not be compilable, but second.cpp will.

//second.cpp
#ifndef SECOND_CPP
#define SECOND_CPP
#include "first.cpp"

class myClass
{
  public:
    myClass()
    {
      myNS::justAnyNumber = 5;
    }
}
#endif

One remark: I think your usage of cpp files is a bit weird. The compiler will not complain, but any programmers looking at this will, because your are essentially using cpp files for what most programmers would put in header files (.h or .hpp). Since experienced programmers, as they look through source code, often open only header files to know what is in the code, they will be pissed off if they …

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

There are many more options available than the two you mentioned, but without details on what you are exactly trying to achieve, it's hard to tailor the answer. I don't know Qt at all, but I have done quite a bit of GUI, so let me give a few "generic" options that you could consider, depending on what your needs are:

1) Composition: basically, you can allow your class (page) to include polymorphic objects to customize it. This would be appropriate if the code in the class (page) has a lot of other stuff that is common to all cases (as you mentioned that the pages are basically the same) and you don't want to copy-paste that code for each new customized page. This option imposes a clear divide between the basic and custom functionality and data. Say, all you need to customize is the response to a button in the page that is clicked:

class ButtonHandler {
  public:
    virtual void OnClick() = 0;
};

class CustomPage : ... Qt stuff ... {
  private:
    ButtonHandler* hdlr;
  public:
    ... lots of Qt stuff ...
    //give a button handler on construction
    CustomPage(ButtonHandler* aHdlr) : hdlr(aHdlr), ... { ... };
    //handle the button click
    void OnClick() {
      if(hdlr)
        hdlr->OnClick();
    };
};

class HelloWorld : public ButtonHandler {
  public:
    virtual void OnClick() { Message("Hello World!"); };
};

int main() {
  CustomPage page1(new HelloWorld); 
  ...
};

2) Inheritance: have a base (page) class for all the common functionality and provide protected virtual functions …

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

>>how can I do it without pointers?

Like this:

class Agent {
private:

    struct AgentStruct {
        std::string agentName;
        double pID;
        double mID;
        AgentStruct *nextAgent;
    } AgentP; //notice no * star sign.

public:

    Agent(std::string);
    void SetNextAgent(const AgentStruct&); //notice pass-by-reference
    Agent* GetNextAgent();
    void SendMessage();
    void ReceiveMessage();

};

//...
/*
 * The constructor we are required to implement.
 */
Agent::Agent(std::string name) { //no need to create AgentP
      AgentP.nextAgent=NULL; //notice dot instead of arrow.
      AgentP.agentName=name; //in C++0x, this could also all be in the initialization list instead.
      AgentP.pID=setPID();
      AgentP.mID=AgentP.pID;
}

Of course, if there is another reason (that you didn't mention) why you need to use a pointer for AgentP, it is fine to do it, but remember to delete it in the destructor of the Agent class (or better, use a smart pointer).

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

The reason for this problem is that array indexes in C/C++ start at 0 and end at N-1 (not N). So One[31] is not part of the array "long One[31];" it is actually one long beyond the last element of the array. The last element of the array is actually One[30]. The reason why it is the same as Two[0] is that the array Two starts immediately after the array One.

>>I would post all the code, but its several thousand lines
How could you write several thousands of lines without knowing this basic rule of C/C++?

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

What has been said so far is all true. As Milton hinted to, what I would say is the main difference between struct and class is in the traditional use of them (or programmer conventions). Most programmers and most code that I have ever seen make use of struct almost exclusively for so-called Plain-Old-Data types (POD-types) where the main purpose of the type is to hold a bundle of data members (but not necessarily the only purpose). For example, a simple 3D vector type like this would usually be implemented with struct:

struct MyVector3D {
  double x, y, z; //just holds the three coordinates, no functionality implemented.
};

On the other hand, a type that is mostly a functional element (e.g. fairly complex member functions with some internal, encapsulated data members) and possibly in an inheritance tree (with virtual or pure virtual functions) would generally be declared as a class, by convention.

Of course, the language itself does not force you to obey those conventions and you are free to break them, but that will mostly confuse other programmers (and yourself too!). It is also a good way to start designing a struct or class by thinking about whether it is more of a data container or more of a functional element.

Of course, sometimes there are types that are in-between where it is not clear-cut (e.g. a vector type with several methods for vector arithmetic or magnitude calculation or whatever, and possibly derived into a position …