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

If you know there is a fixed number of grades/courses, then you actually won't need to check for the newline.

If you do want to read until the newline, then you need two steps. First, you read the entire line into a string, and then, you use the string to read in all the other variables (using a stringstream that acts as a fstream but on a string, found in #include <sstream>). Here is how to add this:

string s;
getline(dataIn, s); //read the entire line until the newline character, into string s.
stringstream ss(s); //create a stringstream to read from the string s.

while( (counter < 8) && //while not at the end of counter. 
       (ss >> arg.gradepoint[counter] >> arg.hours[counter]) ) //and stream is not empty.
{
     total = total + arg.gradepoint[counter];
     counter++;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It appears that this is just a little compiler flag mismatch. You should follow the instructions here, and it should work.

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

The lines 84, 86, and 87 should disappear. guessArray is not really used and its use is corrupt. numberofGuess is the same as MaxNumberOfGuesses, just keep one.

The error you are getting is caused by the fact that "numberOfGuess" is not initialized to any value (defaulted, in debug mode, to 0). What value did you think it had? It is not because you name the variable MaxNumberOfGuesses that the compiler will give it a good value. In any case, to declare a static array, such as UserResponse, you need a constant value, so a variable is not correct either. So, say you want maximum 10 guesses, then, at line 85 and 93, it would be:

const int MaxNumberOfGuesses = 10; //notice the 'const' here
//..
Guess* UserResponse[MaxNumberOfGuesses]; //now this array has non-zero, constant size.

It seems that with the above changes, it should compile and run.

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

The type T is equal to the type Position (T is a placeholder for the type that you put between <> when declaring the stack). It says so in the error message: "[with T = Position]".

You need to push a variable of type Position, there is absolutely no doubts about that, don't try anything else, it won't work.

The reason you are getting errors with the code I suggested is because you don't have a constructor for Position (I'm sorry I didn't point that out early, it's just that the coming standard won't require it and I got used to that). So, you need to add a few things to your Position struct:

struct Position
{
  int x,y;
  Position(int aX,int aY) : x(aX), y(aY) { }; //constructor.
  bool operator ==(const Position& rhs) const { return ((x == rhs.x) && (y == rhs.y)); };
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your stack is a stack of Position objects. You need to push Position objects onto it, not integers. For example, at line 55, you could do this:

S.push(Position(Start.x -1,Start.y));
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

On line 153, I think you should be using i and j to compute the heuristic (otherwise, it would get over-estimated, which is bad for the algorithm, it will basically break it).

I don't think that using the Manhatan distance is OK if you are allowing diagonal motions. The heuristic should always be less than the actual travel cost (otherwise the algorithm breaks). The manhatan distance will give you the distance if you never take a diagonal, but it will very often be shorter if you do (unless the travel cost of a diagonal is 20 and not 14).

That's all I could spot in there.

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

>>Is there a way to fix this issue?
You could just check if the absolute value is under epsilon and then output zero instead (as an integer). That's just for cosmetics, but I don't think anyone would mind (seeing -0.00 is very typical, nobody cares).

>>Should I worry about actually making those values equal to 0?
You should not worry about making the values equal to zero. You can display them as exactly zero as I said above, but setting the actual value to zero is meaningless. One thing that you can do, as part of the Gaussian elimination, is set the values that are cancelled to zero instead of the result of a subtraction with itself (that is also slightly more efficient... not that you should ever worry about efficiency with a Gaussian elimination since it's already (almost) the worst algorithm for solving a linear system).

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

Your creation of the matrix is not correct. First, when making a new matrix, the elements of it are not automatically set to zero, you have to do that. Second, at line 145, I think you have the wrong index for S (it should be j, not i).

At line 153, you cannot really compare a floating-point value to 0 (because they rarely will be exactly zero). You should check that the absolute value is less than some small number (epsilon, like 1E-10 or something similar).

At line 169, at this point, the value of MatrixA[j][j] should be 1.0 (it was just normalized) so there is no point in using the value in the matrix, just use 1.0.

At line 177 and 179, you should be using matrix B, not matrix S (remember, the matrix S is just for testing the result, it should not be part of your Gaussian elimination).

From line 169 to 180, I think you should avoid using a division by MatrixM[j] for the "scale" variable. This is because that number could very easily be zero, in which case, it should still work. So, instead of dividing row i by that number and subtracting row j from it, you should subtract "row j multiplied by the inverse scale" from row i.

For the rest, it seems alright.

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

All your huge switch-statement does is:

get a seat selection X
-> if X is out-of-range or not available, then ask for another seat selection.
-> otherwise, reserve seat X

Your C++ code for doing this should be no more than 5-6 lines of code long, if you just follow the above pseudo-code (and use an array to store the seats as reserved or not). I wish I could just write the code for you, but this is something for you to do on your own. Just a little example on how to use an array:

#include <iostream>

int main() {
  char my_array[9]; //declares a fixed-size array of 9 characters.
  my_array[0] = 'a'; //access the first element of my_array with index 0 (indices start from 0).
  my_array[2] = 'c'; //e.g. this sets the 3rd element to the character 'c'.
  //you can loop through an array with a for-loop:
  for(int i=0;i<9;++i)
    my_array[i] = ' '; //this sets all elements of my_array to the space character.
  //you can also access the elements for printing them:
  for(int i=0;i<9;++i)
    std::cout << my_array[i] << "|"; //prints all elements separated by '|'.
  std::cout << std::endl;

  return 0;
};

In the above, you have all the information you need to turn you thousand-something lines of code to less than a few dozen lines of code.

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

You are definitely just missing a library of some kind. After searching on google for some of these functions, it would seem that these are not part of some off-the-shelf library (win32 or something). I would guess that these are part of the SIP (?) code that you have. Try making a in-file search for some of these function names in all your source files. You should be able to figure out in which source files these functions are defined and make sure you have linked those compiled units too (remember that the ordering of linked objects does matter!).

If you don't find the functions is the sources you have, try looking at the includes of the files that use those functions and find the header files in which they are declared (you have those headers for sure since you were able to compile them). Then, you will just need to figure out which libraries these header files are supposed to link to.

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

Here are a few cases with explanation to make it clear what they are:

class Hop {
  public: //could be any scope
    //this defines a nested class/struct inside Hop, this is a _type_ (not data member).
    struct NStrct{
      int nCount;
    };
    //the above nested type can be used to defined data members:
    NStrct d1; //this is a data member (non-static) of type Hop::NStrct
    static NStrct d2; //this is a static data member of type Hop::NStrct
    //this defines a data-member and a nested class/struct:
    static struct NStrct2 {
      int nCount;
    } d3; //d3 is a static data member of type Hop::NStrct2.
    NStrct2 d4; //this is a non-static data member of type Hop::NStrct2.
    //you can also define static const data members:
    static const int d5 = 42; //since "int" is a built-in type, you can initialize d5 in the class declaration.
    static const std::string d6; //since std::string is a class, d6 has to be initialized outside of the class declaration.
};

//in the cpp file:
const std::string Hop::d6 = "Hello World";

int main() {
  Hop obj; //declares an object of type Hop.
  //The non-static data members are accessed with an object:
  obj.d1; obj.d4;
  //The static data member are accessed with the class:
  Hop::d2; Hop::d3;
  Hop::d5; Hop::d6;
  //nested types are also accessed via the class:
  Hop::NStrct v1;
  Hop::NStrct2 v2;

  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

When you pass the object by value (not pointer or reference), a copy of the object is made and used as the parameter. Because the parameter is of type Base, the new object (the copy of the passed object) is of type Base, regardless of the type of the object that is given as parameter to the function call, as long as there is a way to make an object of type Base from the object that is passed to the function call. By default, the compiler generates a copy-constructor for Base that takes an object of type Base by reference (to which an object of type Der can be implicitly cast to).

In summary, here are the cases:

#include<iostream>

class Base {
  public:
    virtual void fun()
    {
      std::cout << "base" << std::endl;
    };
};

class Der : public Base {
  public:
    void fun() {
      std::cout << "Der" << std::endl;
    };
};

void func_by_value(Base b) {
  b.fun(); 
};

void func_by_ref(Base& b) {
  b.fun();
};

void func_by_ptr(Base* b) {
  b->fun();
};

int main() {
  Base b;
  Der d;
  b.fun();          //output: "base"
  d.fun();          //output: "Der"

  func_by_value(b); //output: "base"
  func_by_value(d); //output: "base"
  func_by_ref(d);   //output: "Der"
  func_by_ptr(&d);  //output: "Der"

  return 0;
};

If you want the equivalent of passing-by-value, i.e. you don't want to allow modification of the original object, you can pass by const reference.

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

Just for the record, if you #include <algorithm>, you can replace lines 20 to 38 in template<>'s code with the following:

TVec::iterator iter = std::find(v.begin(), v.end(), who); //returns the iterator that matches 'who'.
  if(iter != v.end() ) {
    v.erase(iter);
    std::cout << who << " is removed" << std::endl;
  } else
    std::cout << who << " is not on list" << std::endl;

As for the compilation error. There shouldn't be one with either template<>'s code or the above. When you get an error that says "instantiated from here" this is not the error it is just a kind of back-tracking of the error. There must be a real error message before that message (this "instantiated from here" just tells you where the error comes from in your code, but the actual error is usually deeper down). The only source of error I can think of is if the type of "iter" is not correct (make sure that if "v" is of type std::vector<std::string> , then "iter" should be of type std::vector<std::string>::iterator (or equivalently with a typedef).

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

Make search in all your makefiles for the keyword "-Wstrict-prototypes" and remove it. This is a compiler option that is not necessary (i.e. just a warning) and it must be specified literally somewhere in the makefile (or in many makefiles) so you should be able to just remove it. If you are lucky, the person who wrote the makefiles did his job correctly and lumped all the flags into two variables like CFLAGS and CXXFLAGS (that's just a naming convention, the actual names could differ), in which case, you only have to remove it from CXXFLAG (the C++ compiler flags).

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

Well. Qt has fairly straight-forward OpenGL support through the QGLWidget, for example this simple NeHe tutorials in Qt. For all the pan/rotate/zoom and select operations, I'm not sure if there are much off-the-shelf components or actions that can do this. Fortunately, this isn't all that hard to implement with OpenGL transforms and the basic mouse-events from Qt.

If you want a more complete tool, I have heard that VTK is very feature-rich, but I have never used it.

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

Your question makes very little sense. I think you have a confused idea of "heap". There are two things that are commonly referred to as a "heap".

Formally, a heap is a type of data tree-structure typically used for implementing a priority queue. Wiki.

Colloquially, people say "heap-allocated memory" or "memory from the heap", when they really should be saying "dynamically allocated memory". Wiki. The reason people use the term "heap" is because every program is assigned an entity that manages the dynamic allocation of the memory for the program, and that entity is (almost) always implemented using a heap data structure (or something very similar). Now, using the term "heap" to designate the entity that allocates dynamic memory has become ubiquitous in programming vocabulary, compiler/software error reports and operating system functions.

So, in light of the above, for your questions:
>>How many heaps are there for each?
There is one heap per process (exe or dll running). So, if those arrays are all in the same program, there is just one heap. That question makes no sense.

>>Since there are two sorting algorithms, bottom-up and top-down,
I would assume only one is used (or maybe a dual version). This is implementation specific, and it shouldn't be of any concern to you.

>>Are there 2 heaps for each entries?
Again, no. There is one heap, regardless of what you allocate on in, there is always just one …

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

>>I'm wondering how to correctly link an array to a class.
Well, you can link an array to a class, but that's probably not what you want. What you want is to store an array in a class. This can be done like this:

class MyClass {
  int values[10]; //this will store ten integer values in an array inside an object of class MyClass. 
};

Of course, the array can be in either private, public or protected scope. Basically, in a class, you can store any variable that you could store as a local or global variable, and are declared the same way.

Your problem also says that you should use polymorphism. This means that the array of Guess that you would store in GuessingGame would have to be an array of pointers to Guess objects. The reason why you need to store pointers is because the objects in the array are not really Guess objects, but objects of a class derived from Guess. So this would be more appropriate:

class GuessingGame {
  public:
    static const unsigned int max_number_of_guesses;
  private:
    Guess* guesses[max_number_of_guesses];
  public:
    GuessingGame() {
      //you need to inilialize guesses to NULL:
      for(int i=0;i<max_number_of_guesses;++i)
        guesses[i] = NULL;
    };
    ~GuessingGame() {
      //and, you need to delete them afterwards:
      for(int i=0;i<max_number_of_guesses;++i)
        delete guesses[i];
    };
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

-Wall stands for -W (warning) and all (for "all"). It just is a command-line argument to the compiler to tell it to report all warnings about your code. If you don't enable this, the compiler will only report errors that prevent it from compiling the code. If you enable all the warnings, it will report many things that are indications of possible mistakes that you could have made (e.g. using single = (assignment operator) in an if-statement, casting a double variable to an int (that will result in a loss of information), and many other little things that can come from either typos or poor coding practices (like C-style casts)). This is a general rule for good programming practices: "enable all warnings and treat them as if they were errors" (i.e. fix your code such that the compiler doesn't complain about anything).

When you are using an IDE (eclipse, VC++, Code.Blocks), you typically enable all the warnings via the "build options" for your project (in the menus, find "build option" or something similar, and then you should be able to find a large list of "compiler options" from which there are several options that relate to warnings, they pretty much should all be enabled (checked)).

Personally, I don't understand why all warnings are not enabled by default, because they should (i.e. it should be that compiler options are used to disable warnings that are all enabled by default).

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

>>Sound simple?
Not simple, but only a little twisted.

I'll ignore the fact that "Sound simple?" is the only question you asked, and I'll go ahead and give you some hints by solving a similar problem.

Long story short, the solution to your problem lies in "recursion" (a function that calls itself). Let me show a little "Hello World" decoding program. Assume you have an array of numbers, each number corresponds a letter, but lets assume that one of those numbers can correspond to two possible letters (thus creating this combinatorial problem). So, lets say that 0 = 'H', 1 = 'e', 2 = 'l' or 'o', 3 = <space>, 4 = 'W', 5 = 'r' and 6 = 'd', that would be enough to "encode" the "Hello World" message into the array {0,1,2,2,2,3,4,2,5,2,6}. To decode the array, until I find a match for the "Hello World" string, I could do the following recursive function:

#include <iostream>
#include <cstring>

const char actual_message[] = "Hello World";
const int encoded_message[] = {0,1,2,2,2,3,4,2,5,2,6};
const int num_characters = 11;

bool decodeMessage(char* CurrentGuess, int index) {
  while( index < num_characters ) {
    switch (encoded_message[index]) {
      case 0:
        CurrentGuess[index] = 'H';
        break;
      case 1:
        CurrentGuess[index] = 'e';
        break;
      case 2:
        {
          CurrentGuess[index] = 'l'; //start a branch for the 'l' possibility.
          if(decodeMessage(CurrentGuess, index + 1))
            return true; //if it worked, then return true.
          //if it didn't work, recurse on the 'o' branch.
          CurrentGuess[index] = 'o';
          return decodeMessage(CurrentGuess, index + 1); 
        };
        break; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Can I use the new shared_ptr to access my class without worry, (assuming the instance won't be destroyed)?
Yes. The "thread-safety" of shared_ptr has to do with modifying the pointer value stored in the shared_ptr. In that regard, the share_ptr has exactly the same thread-safety as a raw-pointer (which is basically none). When it comes to dereferencing the pointer (accessing the object it points), that becomes the domain of the thread-safety of that class (i.e. if your class is thread-safe, accessing a shared object through a shared_ptr will be thread-safe). The thread-safety concerns with shared_ptr only have to do with threads that share the same pointer (not copies of the pointer). But, dereferencing a pointer is always thread-safe by itself (it is a read-only (const) operation) as long as another thread is not changing that pointer's value at the same time.

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

Don't change the extension to .a (.lib and .a are not exactly the same thing, but equivalent). It appears that proper way to do it is to omit the extension in the command-line (but leave it in the filename), as such:

$ g++ Host.cpp -l libMkDll -o Host.exe

Given "-lfoo", the ld.exe of MinGW will first look for "libfoo.a" if it is not found, it will look for "foo.lib". In other words, with "-llibMkDll", it should find the file "libMkDll.lib" (note that normally, you don't name .lib files with the "lib" prefix).

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

There is one thing to observe. What is really expensive in your code (and in many linked-list implementation) is the very frequent dynamic allocation of memory of small chunks (each node). Because you know, from the start of this function, how much memory you will end up allocating for the additional amount of nodes in the LHS list, you should find a way to use that information to your benefit. However, the structure of a linked-list makes this very difficult (i.e. ideally, you would want to allocate a large block of memory, and use placement-new operator to create your new nodes in that space, but the book-keeping that this will require is a going to be very difficult to implement). So, you really are stuck having to do all these incremental and numerous dynamic memory allocations.

For the rest, your algorithm seems to be doing what it should and I can't think of a way to accomplish that more efficiently.

However, you can accomplish something slightly different much much more efficiently. If you implement move-semantics instead of copy-semantics for your linked-list, you can avoid the memory allocation completely. By "move-semantics" I mean that the RHS list would be transferred into the LHS list as they are merged together. If you take the RHS list as a non-const reference, you could basically just empty out the nodes of that list and link them to the nodes in your LHS list. At the end, the RHS list will be empty …

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

You would need to pass "ref" and "out" by non-const reference. This also means that your call with bind will have to be supplied with non-temporary variables, e.g.:

...
    template<typename inputItr, typename outputItr>
    void operator() (T const VALUE, inputItr& ref, outputItr& out)
...

//I call the functor like this
InputIter augRefItr = augRef.begin(); //get a non-temporary iterator.
std::for_each(augBase.begin(), augBase.end(), std::tr1::bind(fastRowSum<T, U>(), std::tr1::placeholders::_1, augRefItr, matchingCost_Itr ) );
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Aren't you supposed to write:

$ g++ Host.cpp -l libMkDll.lib -o Host.exe
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It seems you are doing the steps correctly (I'm not sure since I rarely use DLLs and Windows). To avoid the name-mangling problem. You need to make all your functions "extern "C"". This tells the compiler to use C name-mangling (which is basically no mangling at all). Every compiler has a different pattern for name-mangling in C++ (it is not that GCC is not "respecting" export names).

The dlltool call will try to "publish" export names that it contains and link those names to functions in your .o file. But I would assume that it will not be looking for GCC mangled names. So, either use extern "C" to disable the mangling, or try to find an option in dlltool that creates the exports in a way that it looks for GCC mangled names.

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

Referring to the dox, the following should work:

typedef itk::Image<Node, 2> ImageType;
itk::ImageRegionConstIterator<ImageType> imageIterator = 

  itk::ImageRegionConstIterator<ImageType>(image, region);

  // make a vector of pointers to particular nodes
  std::vector<const Node*> nodes; //note const pointer (because ImageRegionConstIterator is const too.
  while(!imageIterator.IsAtEnd())
    {
    nodes.push_back( &(imageIterator.Value()) ); //Value returns a const ref.
    ++imageIterator;
    }

It would seem that GetIndex() would also be a viable option. But the above is good.

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

C++ Standard 7.1.2/4 and 3.2/3 (One-definition Rule):

An inline function shall be defined in every translation unit in which it is used.

In other words, all inline function (if the compiler so decides) have to be defined (have their implementation) in a header file (unless you want to get into the messy business of #including cpp files). And, any function that is defined in the header file has to be marked as inline, otherwise it will break the one-definition rule (even if the function clearly wouldn't be inlined by the compiler).

C++ Standard 9.3/3:

An inline member function (whether static or non-static) may also be defined outside of its class definition provided either its declaration in the class definition or its definition outside of the class definition declares the function as inline.( Note: member functions of a class in namespace scope have external linkage. Member functions of a local class (9.8) have no linkage. See 3.5. — end note )

So, either one is OK, and both are OK as well. It basically doesn't matter where it is, as long as it is there.

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

>>Is the only overhead that I would have to then iterate through the image and delete all of the nodes when the image is destructed?

I would hardly call that an overhead unless you are making new images and destroying old ones all the time. The real overhead is indirection and memory spread. Assuming that Image<Node> would store nodes is contiguous memory (std::vector<Node> or something similar), then traversing the nodes linearly will be much more efficient than if you had a vector of pointers to heap-allocated Nodes. This is because you have to fetch the memory in the vector to get the pointer value, then you have to fetch the memory at that pointer value (address) which could be very different place and far-between. This breaks memory locality and will be the biggest overhead that you will suffer.

>>That is, what are positives and negatives to each approach and when would you use one over the other?
If you need to store base-class pointers because of dynamic polymorphism, then do so. Otherwise, I don't see any real advantage to it.

As for the bigger issue, typically, you want to abstract away the reference to your nodes. I would suggest you take a look at the PropertyMapConcept in Boost Graph Library. Basically: if you have a vector of Node pointers, then the fastest way to access one Node at any time is by its pointer; if you have a vector of Nodes, then the fastest way to …

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

You do know that, in matlab, all you need to do to solve a linear system is to write x = A \ b; where b is a column-vector and A is a square matrix. That's it, you don't need to use the function you posted (as I assume you didn't write it, so it means that you are allowed to use whatever you like). As for turning the equations you posted into a standard linear system formulation, well that's the question of the assignment, nobody's going to do that for you.

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

>>but in my opinion you will alienate a LOT of windows users.
LOL.. if anybody is alienating windows users, it's microsoft. And, btw, most build systems like qmake, cmake, make, and bjam, are completely cross-platform. You might have to install a small piece of software to use them in windows, but these software are free and very small anyways. What is definitely not cross-platform are IDE-specific build systems (like vcproj from Visual C++). It is by far preferred to use a OS-agnostic build system for any kind of "professional" development. It's very annoying to have to reconfigure the build from scratch on every new IDE or OS you decide to use or switch to for a project.

>>End users hate dependencies like this.
The end users don't recompile your program. If they don't need to recompile your program, they won't need anything more as dependency than what your program requires (regardless of what build tool you used to compile it). But if they do want/need to recompile it, you certainly don't want to require them to have a particular proprietary IDE (like Visual Studio or something else), that's why people use makefiles or other build systems that are free and not dependent on an IDE.

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

LGPL and GPL are not the same licenses. MySQL is under GPL, it's not compatible with LGPL. The main difference is that GPL forces all "derived works" to also be licensed under GPL (or in the case of MySQL, under a compatible license, approved by the Open Source Initiative). While the LGPL, doesn't enforce that propagation of the license if you are only using it and not modifying or adding anything to it. You cannot decide to license your stuff under LGPL if you are using MySQL. The only real debate is whether simply using the client-side binary and API is considered "derived work". IMO, MySQL would be better off using LGPL at least for their client-side libraries, it would be less trouble and increase their user-base.

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

>>Incidentally, a non-POD can also be value initialized if it does not have a (has a trivial) constructor. eg.

That's true, I guess you managed to pick the one example that falls into the category (8.5/5):

— if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;

But I guess your example would fall under POD when the new standard comes in.

The point still remains, it is not recommended to create variables without giving them an explicit initial value, mostly because for good form, in parts because the rules that govern whether or not an "uninitialized" variable will be zero or not are not trivial to understand and can easily change for a small change in the content of a class declaration.

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

What happens is that the default constructor for the object is invoked (which in this case happens to be 0). Try doing it with an object that doesnt have a default constructor and you will see what I mean.

@L7Sqr: I'm sorry, but I have to correct your statement. I think it is an important point to clarify. Primitive types such as int or int* do not have a default constructor (or, equivalently, their "imaginary" default constructor does not initialize the memory in any way). However, there is the concept of default-initialization in C++ which is invoked with the following syntax:

int* b = new int(); //the int to which b points to is default-initialized.
struct Foo {
  int value;
  Foo() : value() { }; //the "value" member is default-initialized. 
};

When this default-initialization is used one of the following happens (C++ Standard 8.5/5):

To default-initialize an object of type T means:

— if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is an array type, each element is default-initialized;

— otherwise, the object is zero-initialized.

The standard also clearly states at 8.5/9 that, if no initializer is specified for an object of POD-type (which includes primitive types), then the object and any of its sub-objects have "indeterminate initial value".

Basically this means that the following this true (and can be tested to be true):


       
L7Sqr commented: Thanks for the clarification. +1
jonsca commented: Good information +7
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>so I didn't have to... build them(?)
To help clarify, "building" is when you have a bigger project that requires several source files to be compiled into different building blocks (static libraries or shared libraries (DLL)) and then put altogether in a non-trivial way. That's all it means. Basically, it is when a single command line cannot do everything required, then there needs to be some sort of script that does a sequence of operations (mostly compilation commands). The tools that do that automatically are called build systems or build tools (common standalone tools are qmake, cmake, autoconf, and makefiles (but makefiles are not really automatic, you basically write the script from scratch and it's really not trivial to do)). All IDEs also have a built-in build tool (basically, when you start a project or solution in an IDE and add sources/headers/include-paths/libraries to the project, you are basically using the build tool of the IDE to construct this underlying building script that will be invoked with you hit the "build" button).

If Qt Creator can build a debug version, it can certainly build a release version. Check the options (like "build options" for the project). This will, most likely, be the easiest of all.

@gerard4143: writing makefiles is such a voodoo black-magic kinda thing. I wouldn't wish that on my worst enemy. In this case, either qmake or cmake are directly and very easily usable with Qt, that is by far the easier option, if Qt Creator …

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

Yes, that's right. The conversion from Degree to Radians is upside-down. It should be Pi / 180. As so:

#include <iostream>
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
using namespace std;

int main() {
  double angle_in_degrees = 60;
  double angle_in_radians = angle_in_degrees * M_PI / 180.0;
  cout << "The cosine of " << angle_in_degrees 
       << " is " << cos(angle_in_radians) << endl;
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

When a function is taking in a "const char*", it is only saying that it will not modify the data pointed to by that pointer. It doesn't mean that you are not allowed to change the data. In other words, a non-const pointer can be implicitly cast to a const pointer, but not the other way around. If you have a const pointer, you cannot assign it to a non-const one, because the constness of the original pointer is like a "promise not to modify" (a promise the compiler "forces" you to keep), so casting to a non-const pointer would be breaking that promise. However, if you have a non-const pointer there is no promise attached to it, so you can easily pass it to a function that promises not to modify the data.

So, for your problem, the solution is really simple when you consider what I just said:

#include <iostream>
#define MAX 1000
// 3rd party stuff
void ConstPtrMethod(const char* s) {
    std::cout << s << std::endl;
}

// My stuff:
int main() {
    char* Buffer; //remove the const here.
    for (int i = 0; i < 10; i++) {
        sprintf(Buffer, "%d", i); //since Buffer is non-const it can be modified
        ConstPtrMethod(Buffer);   //Buffer can be directly cast to a const char*
    }
}

NOTE: You do understand that your simple example is not a working piece of code, right? You would need to allocate memory for Buffer to point somewhere before you do anything else! So …

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

yes, but I would still recommend making the initial value explicit (as in stinker() : pointer(NULL), age(0) { }; . You are basically asking the person who reads your code to be aware of "value-initialization of POD type means zero-initialization". This is not so common (many people wouldn't even know the difference between default-initialization and value-initialization). This SO thread might clarify things for you.

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

I have to say that your implementation of the backsub looks very bizarre. I have implemented back-substitution is several matrix numerical methods (PLU, QR, HH, Cholesky, SVD, etc.). I have checked them, and they look nothing like yours. Yours looks more like forward-substitution.

First, your bounds at line 14 and 16 are almost certainly wrong. You are definitely skipping elements. I think the bounds of these loops should both be j and not (j-1), because you want to visit the row/col before j, using (j-1) will skip that row/col. And that simply doesn't make sense.

Second, you are, oddly enough, traversing the array in a forward direction while doing back-substitution. You know, it's called back-substitution because you start at the end (last element of the diagonal) and work your way backwards. You are doing the opposite, and I cannot possibly understand how that could still work. If you look, for example, at this site, under the back-sub algorithm, you will notice how the elements are necessarily traversed backwards "(i=n,n-1,n-2,...1)" in the formula.

Finally, the fact that the diagonal is correctly inverted is quite meaningless, the diagonal is almost guaranteed to invert correct if you didn't screw up completely.


PS: Don't ask me to post my back-sub algorithm, it bears no more information than that in the formula at the link given above. And I presume that if you just wanted a ready made algorithm, you would have gotten one already from the …

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

I am by no means an expert on these things, so the following is just an opinion.

I think that the wikipedia section on Linking and derived works under GPL is pretty interesting. It seems to be a pretty vague issue.

You also have to understand that licensing issues are rarely if ever pursued unless there is big bucks to be made. So, basically you don't have to worry about this until you make your first million with this software of yours. So, distributing a free-software in closed-source is probably not gonna get MySQL to sue you for all the non-profit you've been making (i.e. $ZERO$ ).

Finally, MySQL is probably not concerned very much by the use of the client-side code, they are probably happy with it. All their trade "secrets" (or what would be really secret if it was not GPL) is all in the server-side (all those fancy database query algorithms and data mining). And, if you ever decide to sell and make money with your software, you could just switch to a proprietary database system which wouldn't be hard at all anyways.

Remember that GPL is so that either you distribute for free or you don't. So, either you distribute your software open-source and let it take a life of its own in the open-source community. Or, you don't distribute your software until you decide that either it is serious enough to replace GPLed parts by equivalent proprietary (or BSD. …

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

I think the only problem is that on line 95 and 103, you are using "alp" instead of "alpha". For the rest, it is correct. To some extent, your use of outputting the value of alpha and beta by passing them by reference is correct but not necessary. If you have a function that has one output value (alpha and beta, respectively) then these should probably be the returned value and not a parameter. This is merely for good form though, not a requirement.

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

If you want some outside classes to access the private members, there are obvious consequences to that and you should by all means try to find a way in your design in which you can avoid other classes or functions to require access to those private members. However, if all fails and you do have to expose the internals, then there are three options from bad to worst:
1) Use a friend relationship.
2) Create an accessor class (one nested class or friend class that exposes complete access to the internals via a set of accessor/mutator functions).
3) Expose all the internal data (i.e. make everything public). That'S pretty bad.

To help with the friendship of classes, it will get annoying if you have to have a list of friend classes and sort-of require the user to register his new class as a friend. If you can use templates, I suggest something like this:

#include <iostream>

#include <boost/bind.hpp>
#include <boost/function.hpp>

template <typename UpdatePolicy> class MyClass; //forward-declare.

struct InnerUpdatePolicy {
  typedef InnerUpdatePolicy type;
  typedef double result_type;
  typedef double (MyClass<InnerUpdatePolicy>::*update_func)();
  update_func mUpdate;
  InnerUpdatePolicy(update_func aUpdate) : mUpdate(aUpdate) {};
  double operator()(MyClass<InnerUpdatePolicy>* aThis) {
    return (aThis->*mUpdate)();
  };
};

template <typename UpdatePolicy>
class MyClass {
  public:
    friend class UpdatePolicy::type;
    boost::function< double() > Update;
    MyClass(UpdatePolicy aUpdateFunctor) : value(42.0) {
      Update = boost::bind(aUpdateFunctor,this); //bind the this pointer to the functor call.
    };

    //as example, MyClass has one or more default functions for the Update:
    double DefaultUpdate1() {
      return 0.0;
    };
  private:
    double value; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You could simply use the Boost.Function and Boost.Bind utilities, as follows:

class MyClass
{
public:
  double Update1();
  double Update2();
  double Update3();
  boost::function< double() > Update;
private:
  float Data1;
 ...
  float DataN;
};

Then, define them as:

class MyClass
{
 int UpdateMethod;
};

void MyClass::SetUpdateMethod(int method)
{
 if(method == 1) 
   this->Update = boost::bind(&MyClass::Update1,this);
 if(method == 2) 
   this->Update = boost::bind(&MyClass::Update2,this);
 if(method == 3) 
   this->Update = boost::bind(&MyClass::Update3,this);
}

Now, MyClass.Update can be called as any other member function.

A slightly more customized version of this would be by using a pointer to the member function and just calling it on this within the Update() function.

daviddoria commented: Very cool, thanks for the suggestion! +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is an age old debate. C/C++ vs FORTRAN. Many people who know much more than I do have more informed opinions on it. I'm sure you can find many many forum threads, articles, and peer-reviewed research papers on the subject. However, you must be careful at only looking at very recent data (anything older than 5 years is basically worthless, things change really fast in the world of computing).

As for performance, check this site out. It basically compares almost every programming language out there on a exhaustive number of benchmark tests, and it is mostly compiled from the last 5 years. The conclusion, after looking at many language-to-language comparisons, is that GNU GCC C++ and C are tied at number 1, followed closely (2 or 3 times slower) by Java-6, Ada, and Lisp, and trailing surprisingly far behind are FORTRAN and Pascal (around 5 times slower than C/C++). I'm sure there are other results that contradict that, but this seems like a fairly neutral benchmark test. Beware of some reported results that are sometimes tailored to favour one language over another (classic in the heated Java vs C++ debates).

Generally, many are of the opinion that performance alone is not the biggest factor. Look at this interesting article for example. The point of often made that computing time is cheap, the programmer's time is not. Basically, FORTRAN (at least the older versions that I am familiar with) is difficult to program in. …

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

Ok, its the file reading that is wrong, I got the same duplicate of ashley by running your code. This should be the file-reading loop:

Prog3.Read_m(Infile);
/***Load Data into List***/
while(!Infile.eof())
{	
  theList.push_back(Prog3);
  Prog3.Read_m(Infile);
};//while

It is due to the fact that some IO stream implementation won't hit end-of-file until a read operation failed.

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

Make sure you don't have an extra empty line at the end of your input file. I'm pretty sure that is the problem. And your original loop for file-reading is correct.

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

Well, there is a simple way to do it if you are restricted to iostream, cstring and cstdio.

A simple modification of L7Sqr's code to use C-strings instead:

std::cout << "First names: ";
    char token[100];
    std::cin.getline ( token, ',' );
    std::cout << "Read token: " << token << std::endl;
    std::cin.getline ( token, ',' );
    std::cout << "Read token: " << token << std::endl;
    std::cin.getline ( token );
    std::cout << "Read token: " << token << std::endl;
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If your tutor told you that overloading the < operator for the Player class would make the tree ordered with respect to that comparison's logic, then he made a mistake in his implementation of the Tree class. This implementation of the Tree class compares the values of the pointers, not the objects they point to. This is either a mistake on his part or you have misunderstood how the ordering in the Tree should occur (if the Tree code is correct, it means that they ought to be ordered by the pointer value, not by value).

I don't understand way your tutor would provide a Tree implementation when there is a standard implementation of a sorted list, it is called std::set. It could be used as follows:

bool comparePlayers(const Player* p1, const Player* p2) {
  if(!p1) return false;
  if(!p2) return true; //relegate all NULL pointers to the end, if they exist (unlikely).
  return *p1 < *p2; //compare by value.
};

typedef std::set<Player*, bool (*)(const Player*,const Player*)> Tree;

int main() {
  //.. .as before...
  Tree PlayerTree(&comparePlayers);
  PlayerTree.Insert(players[1]);
  PlayerTree.Insert(players[0]);
  PlayerTree.Insert(players[3]);
  PlayerTree.Insert(players[2]);
  PlayerTree.Insert(players[4]);
  for(Tree::iterator it=PlayerTree.begin(); it!= PlayerTree.end(); ++it)
    (*it)->Display();
  //...
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I would first verify with your teacher whether this is really what he wants, because that is not easy to do, in fact, you probably can't do it without an extended IO library (such as conio.h or curses.h).

I would suggest you just avoid the problem and do this:

// input number of sheep in each field
  cout << " Enter the number of sheep sheared from 3 fields for 2008 : ";
  cin >> numberOfSheep1 >> numberOfSheep2 >> numberOfSheep3;

Then the user can enter the three fields, separated by a space.

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

Serialization 101:

class oserializer; //forward declaration
class iserializer;

//create a base abstract class for all serializable objects:
class serializable {
  public:
    virtual oserializer& serialize(oserializer&) const = 0;
    virtual iserializer& deserialize(iserializer&) = 0;
};

//create a serializer class (for saving, o for output):
class oserializer {
  private:
    std::ostream out_file; //hold a file to write to.
  public:
    oserializer(const std::string& filename) : out_file(filename) { };
    
    //Create a bunch of overloads of operator << for each primitive types:
    oserializer& operator <<(const int& value) {
      //save to the file, any way you like (e.g. binary or XML), say binary:
      out_file.write((char*)&value,sizeof(int));
      return *this;
    };
    // ... and so on for all primitive types (unsigned int, char, float, double, etc.)
    
    //Then, write a few overloads to handle some common STL containers (technically you have them all):
    template <class T>
    oserializer& operator <<(const std::vector<T>& vec) {
      *this << vec.size(); //keep a record of the size, this will be useful for loading.
      for(std::vector<T>::const_iterator it = vec.begin(); it != vec.end(); ++it)
        *this << *it; //save all the elements using one of the primitive overloads.
      return *this;
    };
    //so on for the other STL containers.

    //now, write an operator for a serializable object:
    oserializer& operator <<(const serializable& obj) {
      return obj.serialize(*this); //just call serialize.
    };
    //provide one for a pointer too: (or better: a smart pointer)
    oserializer& operator <<(const serializable* obj) {
      return obj->serialize(*this);
    };
};

//now you can create classes like this for example:
class Foo : public serializable {
  int a;
  float b;
  char c;
  public:
    virtual oserializer& …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you look at my last answer to this thread, you will see that you are in case number 5, i.e. you have an object hierarchy with cross-references between objects (via pointers). As with many programming problems there are three ways to solve it: the good, the bad and the ugly.

The Good: Use a library that is already established and highly regarded, if it serves your need. In this case, Boost.Serialization. I know, the code in it is not exactly "simple" for a beginner. But if you can bare it, use it.

The Bad: Make your own home-brewed serializer. This is bad because it is reinventing the wheel and it is tedious to make it robust (or you have to leave it in a fragile state, which is worse). Anyhow, for this, you would have to have a class that handles all the I/O with the file. That class should keep a record of all objects (non-primitive) (by pointer) which are saved so that it doesn't repeat or go into an infinite cycle. I could go on explaining it, but I think you could be looking for the Ugly way instead.

The Ugly: Write a quick and dirty, single serving solution. In this case, you can assume that all drivers can saved as part of the save function of the team object. So, the driver class probably shouldn't save the team pointer that is has. So, in a save/load function in CTeam, you just …