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

This problem is just a matter of the types of "intarray" and "begllts and endllts". If they are of the same type (or compatible types), then you need to show the definition of those types. If they are the same and are primitive types like "int", then there is something wrong. Most likely, the types are not built-in types and you didn't provide an overload for the < > operators. Normally, a custom type would need to provide the compiler with a method to compare them (if you want to compare them and if it makes sense to do so), for example:

struct MyIntType {
  int value;

  bool operator < (const MyIntType& rhs) const {
    return value < rhs.value;
  };
  bool operator > (const MyIntType& rhs) const {
    return value > rhs.value;
  };
};

In the above, the definitions of operators < > will tell the compiler how to handle less-than or greater-than comparisons between variables of type "MyIntType".

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

The typedef that you have shown is a typedef for a "function pointer" type. The format is a bit different than other "normal" typedefs. Here would be the simple format of such a typedef:

[B]typedef[/B] [I]return_type[/I] ([[I]calling_convention[/I]] *[B]identifier[/B]) ( [I]parameter_list[/I] );

This means that the following function signature (or prototype) would correspond to the function pointer type defined below:

//function signature (i.e. declaration or prototype):
int myFunction( char* s, int count);
//corresponding function pointer typedef:
typedef int (*myFunctionPtrType) (char*,int);

Which would allow it to be used as such:

int myFunction( char* s, int count) {
  //do something..
  return 0;
};

int main() {
  myFunctionPtrType p = &myFunction; //notice the syntax here, taking the address of myFunction.

  //now p can be called as if it was a function:
  char s[20];
  int result = p(s,20); //the call syntax is as if it was function.
  std::cout << "The result of calling p was: " << result << std::endl;
};

In the example you posted, the "__cdecl" keyword is simply the calling convention of the function (like __stdcall or __fastcall). These are important when using function pointers across different modules (and possibly different original programming languages). For instance, __cdecl is the default C calling convention and is supported by many other languages, and __stdcall is a standard calling convention that is mostly used by Win32 API to make it essentially callable from any programming language.

There are several other variants of this basic concept of "pointing to a function", which …

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

@Baluba: Borland C++ 3.1 dates back to 1992. It's a 16bit compiler for Windows 3.1. That's prehistoric dude! There has been almost 3 revisions of the C++ standard since then and plenty of extensions to the standard libraries too.

@L3gacy and VernonDozier: If you want the very latest gcc (with best support of C++0x and GNU++0x), you will have to download the source from the Subversion server and then follow the build instructions (it took me a few hours on a laptop to compile it yesterday, and quite a bit less on my desktop computer, like 30min). I guess this is mostly for *nix based systems so I doubt that it can be done as easily for Windows. You are probably better waiting for the official MinGW release, and stick with GCC 4.5.2 for now.

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

I think the easiest way to generate your numbers might be something like this:

double d = (rand() % 3000 - 1500) * 0.001;
d = ( d > 0.0 ? d : 0.0);

This way, roughly half of the numbers will be zero and the other half will be between 0.001 and 1.500. I think that should do it. For the rows and columns being all non-zero, you could do this kinda pseudo-code:

while matrix_has_a_zero_row_or_col(m)
  for each row i
    for each column j
      m[i,j] = generate_rand_number_as_above();

Just write a function that verifies the condition on the rows and columns and repeat the random generation of the matrix until the condition is satisfied. That IMO is the least biased method to do it.

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

>>and my Triangle needs a copy constructor to do a deep copy because of the array.
The triangle class does not need a copy-constructor, the default one is fine. The array contained in Triangle is a static array, it will be copied correctly by the compiler-generated default copy-constructor.

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

I would try defining the Iterator type with a typename:

//in SList class declaration:
  typedef typename SListIterator<generic> Iterator;

Please post the entire error message (it is cut-off in the thread's title).

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

Well, I copied your program (with the modification) as follows:

#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    pid_t           pid;
	/* the identifier for the shared memory segment */
	int             segment_id;
	/* a pointer to the shared memory segment */
	char           *shared_memory;
	/* the size (in bytes) of the shared memory segment */
	const int       segment_size = 4096;

	/** allocate  a shared memory segment */
	segment_id = shmget(IPC_PRIVATE, segment_size, S_IRUSR | S_IWUSR);

	/** attach the shared memory segment */
	shared_memory = (char *) shmat(segment_id, NULL, 0);
	printf("shared memory segment %d attached at address %p\n", segment_id, shared_memory);

    sprintf(shared_memory, "How are you my child?");        //Parent writes

    printf("*Currently written in memory: %s*\n", shared_memory);

	/* fork another process */
	pid = fork();

	if (pid == 0)/* child process */
	{
        if (std::string(shared_memory) == "How are you my child?")
        {
		/** write a message to the shared memory segment   */
		sprintf(shared_memory, "I am fine thank you!");
                printf("Currently written in memory: %s\n", shared_memory);
        }
	}
        else/* parent process */
        {
		usleep(100);//wait(NULL);
		/** now detach the shared memory segment */
            if (shmdt(shared_memory) == -1)
            {
			fprintf(stderr, "Unable to detach\n");
            }
		/** now remove the shared memory segment */
		shmctl(segment_id, IPC_RMID, NULL);
        }
        return 0;
}

When I ran it on my computer (Linux Kubuntu 10.10, kernel 2.6.35.25, compiled with GCC version 4.6.0 (experimental)), it gave the following output, as expected:

shared memory segment 884739 attached at address …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think you counted one 6 too few in that last post about the differences.

Also, with the numbers "f(8) = 24", "f(16) = 64", "f(32) = 160"... and the formula "f(n) = O(nlogn)"... I mean.. talk about obvious! I'm no psychic, but I would predict also that "f(64) = 384", "f(128) = 896", "f(256) = 2048"...

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

As far as I know, this expression:

(("%s",shared_memory) == "How are you my child?")

will always evaluate to false. The first part "("%s",shared_memory)" will first evaluate "%s", which does nothing, and then evaluate shared_memory, which does nothing, and then return the value of "shared_memory" which is a pointer. Then, the equal comparison will compare the pointer "shared_memory" with the pointer to the literal string "How are you my child?". That will always be false because all pointers have a unique value, unless they point to the same place.

You need to use either:

if(std::string(shared_memory) == "How are you my child?")

Or, as I have seen from your code, you seem to prefer C to C++, so I'm guessing you would want to use the old "deprecated" C version:

if( strcmp(shared_memory,"How are you my child?") == 0 )

That should fix it.

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

@pseudorandom:
I don't want to be mean, but I think your implementation is probably worse then the OP's or ravenous' implementation.

You correctly pointed out that using magic numbers is not nice, but you are using them. Replacing magic numbers, like 1 2 3, by anonymous enums with names like ONE TWO THREE, is merely a change from typing numbers to typing letters, but they are magic numbers nonetheless. And it is even worse in terms of additional typing (not to mention that they look disgusting in the code... at first glance, any programmer would look at this code and say: "oh, another piece of s**t code with #defines everywhere"). There is no difference between anonymous enums and #defines when used that way. And there is no difference between #defines and literal magic numbers when the values of them cannot be changed (a define with name ONE has to always be one, otherwise it would be confusing, and thus, mind as well use the number 1 instead). In this case, a number like 3 for the number of points in a triangle isn't really a magic number in the typical evil sense. A triangle has three points, that's the definition of a triangle, there is nothing wrong with using a magic numbers like 3 or calculating stuff without a loop, when there is no other possible number of points in a triangle (it's not like you would have to come back later and change that number!).

I …

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

I'm not sure about the exact problem you have, but I think that reading this FAQ will shed some light on your issue. (You mind as well read that entire page, not just that one question)

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

Overall it is quite ok. I mean, you use indentation correctly, which is important. Your variable names are clear, which is also very important. You did put a lot of comments, which is important for the professor (but not really for any programmer that I know of).

It is a very small and simple piece of code, so there isn't much place for bad style or bad programming practices. But since you are asking for critique, I could have a few things to point out:

1)
In general, it's often better style to collect variable declarations near to where they are first defined (this isn't always possible though). You are using what some people would call C-style variable declarations, i.e., declaring all variables at the start of the function (it comes from an old standard in C that forced all variables to be declared at the start of the function, it's not the case anymore and hasn't been for 20 years or so). This is ok, even some experienced people do it this way, but most people (including myself) would say it is better to declare variables as they are needed, as so:

float centroidX = (xa + xb + xc)/3;
float centroidY = (ya + yb + yc)/3;

//instead of:

float centroidX;
float centroidY;
//... a whole bunch of code here ...
centroidX = (xa + xb + xc)/3;
centroidY = (ya + yb + yc)/3;

First, it has the advantage that you don't have …

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

You have to understand that these expected errors are upper-bounds. I would think the messy curves you see (which is called "variance" btw) mostly have to do with the particular function used. For example, when the range includes a zero-crossing, then the way that the intervals (the small sub-divided intervals) of integration fall around the zero-crossing could have a big effect on the actual error. That would explain the "periodic" error curves you get.

I would suggest that you "sweep" the range of integration and take the maximum error. In other words, say that c = (b-a), then for a value of c (interval size), then pick M values of "a" within the period of the curve (maybe 0 to Pi or something.. maybe even picked at random) and perform the integration. Then, pick the maximum error obtained (from all the a values tried) for a given interval size c. This should get rid of this mess on the graph by eliminating the "chance" factor about where sub-intervals fall. And remember that the important quantity is not the actual curves you plot, but the line that hugs the upper-bound of your error the best.

As for round-off errors and floating-point precision, it might contribute to some small deviation from the expected results, but not that much.

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

Add the keyword "inline" in front of ALL function implementations, as so:

template <>
inline void Matrix<double>::CopyData(double* dest, double* src, unsigned count)

That should fix your problem.

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

Well, from the reference page on static_cast:

It can also cast pointers or references down and across the hierarchy as long as such conversion is available and unambiguous. No runtime checks are performed.

You see, static_cast is a compile-time casting operator. It will never do runtime checks (in fact it can't). I am guessing that proper compilers would warn you about such unsafe casts. But, it is allowed. Say, that for some reason, you have a pointer to a BaseClass, but you know that it must actually be pointing to an object of DerivedClass, then, using static_cast would be faster than the only alternative (i.e. dynamic_cast) and still "safe" (well.. as safe as you are sure of the "real" type of the object pointed to).

@deltamaster: >>you can use reinterpret_cast if you guarantee this operation to be safe, it is usually faster than static_cast.
You are wrong. reinterpret_cast is by far the least safe casting operator and it is not faster than static_cast. Also, in this case, it will not work at all because reinterpret_cast does not perform any shifting of the pointer's value. When you cast pointers to classes up or down the hierarchy, there can be an offset necessary on the "this" pointer, especially when multiple inheritance is involved. static_cast will blindly apply this offset at compile-time, while dynamic_cast will safely apply this offset at run-time (with a check). So, static_cast is not as safe as dynamic_cast, but it has no run-time overhead whatsoever …

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

I find it easy to avoid .NET because I don't see any purpose for it in my own projects (and I don't program with Microsoft products anyways).

It is clear that for all basic programming purposes, .NET is not needed. Just stick to the C++ standard libraries (and no managed code, C# or C++/CLI).

For all other purposes, you will find good C++ libraries to use. Just name your type of application and surely people will find good libraries to suggest.

In my opinion, if your application doesn't fall directly in the niche of the .NET framework (i.e. web applications that rely heavily on security protocols, databases, and networking) there is little advantage to this framework and plenty of drawbacks (performance, memory management issues, not portable, your applications run in the confines of a virtual machine, etc.).

I don't know VS too much (especially the newer versions) so I can't pinpoint a particular option to disable .NET completely (there must be one... otherwise MS would loose like 90% of the users of Visual C++ who program entirely in pure C++). I would say that the best way to disable .NET is to use GCC (MinGW) as your compiler instead (all it will compile is just GNU standard C++.. and none of the MSBS (*) ).

(*) Microsoft Bullshit

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

Your constructor for "testType" has no implementation. So the linker is looking for one and doesn't find it and thus throws: "unresolved external reference" (these words mean that your "reference" in the code, which is the call to the constructor, is assumed to be "external", i.e. found in another compiled library that is linked to your program, and the linker can't find it, i.e. "unresolved").

You need something like this:

template<class elemType>
class testType
{
public:
testType() {
  //something here.. or nothing, but you need the { } even if it is empty.
};
private:
int nothing;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Because an integer can span over several characters (like 1312, i.e. 4 characters), the stringstream finds, by default, the first and longest sequence of characters that constitutes a valid number. And discarding leading 0 characters because in any base, leading zeros are meaningless. But, of course, if you have only a zero, then zero will be the integer returned.

Using io manips, you can probably set it to use a fixed size of 1 character for the integer. However, if you are looking for extracting each digit of the number, then I would just do:

string d = "033116";
int b[6];
b[0] = d[0] - '0';
b[1] = d[1] - '0';
b[2] = d[2] - '0';
b[3] = d[3] - '0';
b[4] = d[4] - '0';
b[5] = d[5] - '0';

std::cout << "digits are: " << b[0] << b[1] << b[2] << b[3] << b[4] << b[5] << std::endl;
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This may sound trivial, but I think that you need to be familiar with everything on this page. I mean, all the stuff on the left menu: IOStream library, String library, STL Containers, STL Algorithms and Miscellaneous. I don't mean to know all by heart of something like that. At least reading the synopsis (first page) of each of the STL containers and algorithms. This will allow you to reason about the choices for the containers and algorithms. Like saying: "I'm gonna use a std::list for this problem because the type to contain is large and expensive to copy, so it is worth the overhead of a double linked-list to gain the efficiency in insertion/deletion operations (which I anticipate to do a lot of)" or "I'm gonna use a std::map for this problem because I need fast O(logN) look-up operations and I don't have keys with the same value"... etc.

About the sorting, I think she was referring to some special linear-time sorting algorithms. If this is actually the answer that is "expected", then I guess I was wrong about the purpose of the question. This is a very theoretical answer since these algorithms are seldom used in practice (because they lack generality, so people use them only in very special circumstances). Sure, in that question, it seems the bucket-style sort would be the best, but only because it is a hypothetical situation where the numbers to be sorted are actually random and uniformly distributed …

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

Having more functions is not more complicated than having less. As long as the code does not get copy-pasted. Recursion is not the answer in this case. I would probably do it like this:

int x = 0;
 
void myAdd_no_check(const double& p) {
    ++x;
    LRPointsDeq.push_back((lrPoint(x, p)));
    ... (more code)
    ...
    ...
};

void myAdd(const double& p)
 {
    if (x > 100)
    {
        x = 0;
        for(deque<lrPoint>::iterator it = LRPointsDeq.begin(); it != LRPointsDeq.end(); ++it)
        {
            myAdd_no_check(it->yVal);
        }
    }
    myAdd_no_check(p);
}

If this function is a member function of a class, I would probably make the "no_check" version private. Otherwise, you can also hide it in a "detail" namespace such that users don't call it directly.

The reason why recursion is not useful here is that the value of x is reset, so when calling the function again, you have a useless check and no real possibility of a recursion of more than one layer. Of course, if all those lines of code end up modifying x to the point that it could reach 100, then the recursive call might be necessary. However, I have to point out the the behaviour of this recursion based on the value of a global variable is really weird (almost undefined). Try to change the design such that a global variable like 'x' is not needed.

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

These questions are designed to see if you know the right tools for the job. Of course, these two questions are extremely simple and they surely don't expect you not to be able to come up with a code that does that. What they are looking for is to see what kind of code you come up with. Since these kinds of constructs come up all the time in programming (filling an array, sorting, transformations, etc.), knowing how fast you come up with most appropriate solution is a good indicator of how productive you are as a programmer.

For these questions, obviously:
1)

void invert_cstr(const char* src, char* dst) {
  std::string str(src);
  std::copy(str.rbegin(),str.rend(),dst);
  dst[str.size()] = '\0';
};

2)

int getRandNumber() { return rand() % 10000000; };

int main() {
  srand(time(NULL));
  std::vector<int> arr(1000000);
  std::generate(arr.begin(),arr.end(),getRandNumber);
  std::sort(arr.begin(),arr.end());
//or:
  std::multiset<int> arr;
  for(int i=0;i<1000000;++i) arr.insert(getRandNumber());
};

You see, the second question is a good example of a simple trick question. By asking you to sort the array, you might be tempted to start explaining some sorting algorithms you most probably learned in basic CS classes (like quicksort, mergesort, etc.) which would probably be the worst possible answer to give (it basically tells them that you'll be reinventing the wheel every day for them!). Another answer could be: "I'm gonna find an off-the-shelf library for sorting", at least they will be reassured that you wouldn't reinvent the wheel, but they still would be concerned that you are not aware that sorting algorithms …

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

Maybe I'm crazy, but isn't your code just equivalent to something like this:

int x = 0;

void myAdd(const double& p)
 {
    x = x % 101;
    ++x;
    ... (do something to p)
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

LoL... I was doing something else and didn't refresh the page and pressed "post reply".

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

First of all, do not use the line "using namespace std;" (or any other namespace) inside a header file. This is bad. You are not supposed to dump a namespace in a header file (it will make people who use your library (including yourself) very angry in the future).

I don't see a particular reason why your code does not compile. It must be the way you compile it. Now, error messages are usually precise, your description of the error was not. Post the error message to make it clear.

Does the error say: "unresolved external reference to 'ListItr::moveForward'"
or does it say: "class ListItr has no member called 'moveForward'"

In the former case, you have not compiled and linked all the cpp files together. You should have a GCC command line like this:

g++ main.cpp List.cpp ListItr.cpp ListNode.cpp -Wall -o MyProgram

(or have all your cpp files added as "source files" in your project, if you are using an IDE like Visual Studio)

In the latter case, you have forgot to include the ListItr.h in one of the source files that use it (but I doubt that since you are sort-of abusing #includes in your code already).

BTW: if this is not for a school assignment, note that std::list (in #include <list>) is a double linked-list with all the functionality you need, and more (and usable with all the neat stuff in #include <algorithm>).

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

Are you sure that "glutil.h" is actually getting included correctly (i.e. have you set the include path). This is the only source of error I can see here.

BTW: you are aware that this glutil library that you are using is far from unique. Just google glutil and you will realize that there are an enormous amount of people who have made libraries called glutil.h (a very lame attempt at making their library "the standard one"..). You should stick with proper standard libraries (like opengl, GLUT, and GLUI, and cross-platform renderers like Ogre3D or VTK).

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

"advanced typedefs"!??!?

Almost all libraries have a number of typedefs (in addition to their classes and functions) to make things convenient (and more abstract).

You might want to take a look at Boost. You'll find plenty of "advanced typedefs" there.

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

>>You don't think it's an issue with the compiler...
It is definitely not an issue with the compiler. You can rule that out.

If there is anywhere in your code a repetition of the form "class player {", then one of them must go.

Make sure you use the header guards.

The code you posted is not the error, unless this was part of a header file that is not guarded. It should be like so:

#ifndef PLAYER_H
#define PLAYER_H

class player
{
    public: int money;
    int roll;
    int spotID;
    private:
    char name[45];
    bool banker;
    void getOriginalValues()
    {

    }
};
player p1,p2,p3,p4,p5,p6;

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

You can get something like Qt Creator for doing GUI stuff and play around with tutorials (like David mentioned). I find that going through tutorial examples is a good way to do something more than trivial console applications without requiring deep understanding yet (if you don't understand, you just reproduce the tutorial examples and then play around with the code). You can start by doing things like a calculator with a GUI. Designing GUIs and putting functionality to it rapidly makes you feel like you are making "real" applications.

For doing 2D/3D graphics programming, I could recommend that you just get Ogre3D. Work through their tutorials. The learning curve if very fast and it looks cool quickly.

With these (or other similar tools), you will be able to make the connection between code you would normally program for console apps, and how to display them in a end-user style GUI or graphics application.

I think the best thing to do at your stage is to come up with a larger project (like a 2D/3D game or some user application) that has some level of complexity in the software engineering sense. You might get inspiration as you work through some tutorials from either your GUI tool or graphics engine of choice. Once you have a bigger project to do, it is much more interesting to try and work it out (as opposed to simple textbook examples) because you have a goal to …

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

1) This line:

class OSG_EXPORT Group : public Node

means that the class Group can be exported. This if because when you compile this code into a shared library (.so or .dll), you can export the entire class. This is rarely used in practice because there are binary compatibility problems with doing that. So, the "OSG_EXPORT" is simply a #define that is probably defined like this (not exactly, you can find it for yourself in their source code):

#ifdef OSG_COMPILING_SHARED_LIBRARY
#define OSG_EXPORT __declspec(dllexport)
#else
#define OSG_EXPORT __declspec(dllimport)
#endif

The above just means that the class' implementation will be exported from the dll it is compiled to, or imported from the dll it was compiled in (if you are using this code outside the source code of OSG).

2) This line:

Group(const Group&,const CopyOp& copyop=CopyOp::SHALLOW_COPY);

just means that if you use the copy-constructor in the default way (i.e. Group g1(g2)), then, the copy will be a shallow copy (meaning the pointers or handles inside the Group object will be copied, but the memory or resources they refer to will not be duplicated; basically, both copies will share a pointer or handle to the same memory or resource). But this function also allows for an optional parameter to make it a deep-copy (probably used like so: Group g1(g2, CopyOp::DEEP_COPY)). The deep-copy refers to the opposite of the shallow-copy, that is, all the resources and memory are duplicated for the new copy of the object.

Personally, …

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

Normally, the error you are getting should occur when you operate on "it" (the iterator in Project). It should not occur during the use of the function empty(). This is not normal. Unless you have corrupted the memory somehow, this error should not occur. Make sure it is really occurring at the call to empty() and not at the first use of "it". I would suggest that you try doing the same without using the managed wrapper (use the Project class directly). See if the error is still occurring. Then, try to remove (comment out) all code between the creation of the "project" variable and the call to project.empty() and see if the error still occurs. If the problem is still occurring (and I doubt that very much!), then call Bill Gates and tell him he sucks! Because at that point the problem must be in the implementation of std::list (which btw, is part of the C++ Standard Template Library.. it is only implemented by Microsoft if you are using Visual Studio... the GNU implementations are usually better (comes with MinGw and GCC)).

BTW: you mentioned "list.h"... I hope that you are actually #including <list> and not <list.h>!!

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

First of all, this line:

template <unsigned long style, const char* type >

is not so good because you can use char* but should avoid using "char*" as a template argument. Make sure this is what you want and be careful when using it.

For your problem, again, I'm not sure I understand exactly. And I think you are confused between should and can be done at compile-time (with templates, classes, enums) and at run-time (with constructors, objects, etc.). If you want to create a list of objects of different type (i.e. different template arguments and ID), you can always use a tuple (from Boost.Tuple):

#include <boost/tuple/tuple.hpp>

template <int i> struct A {
  enum {ID=i};
  //..
};

boost::tuple< A<0>, A<1>, A<2>, A<3>, A<4> > myAlist;

If you want to construct that array at run-time (through a constructor or main function), that is impossible. The complete type (all the types contained in the tuple) has to be known at compile-time.

If you want a unique ID for each instance of the object, that requires a run-time process, thus, this is impossible via templates. Hence, don't dream of being able to have them as const values (compile-time constants, like the switch case requires).

If you want each object to have a unique ID that is const, they would have to each be of a unique type (which is not hard to do with templates and tuples). However, to use this ID outside of the class (i.e. object), …

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

The basic problem in all the codes that you put is this line:

std::vector <A<y>* > vec;

This suggest that you are trying to instantiate a class template A with an integer variable y. This is impossible. All template arguments that are of some primitive type (like int) must be assigned to compile-time constants. This includes literal constants (like 3 or 42), enum values (like enum { value = 2 } ) or const variables (like a global constant or static const data member). Basically, it is like when you create static arrays, the value has to be resolvable at compile-time, and, of course, never change at run-time.

For the rest, I couldn't possibly give any advice, I have no idea what that code you posted is supposed to achieve.

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

This should help you understand what is going on (compile, run and play with this):

int main(int argc, char *argv[]) {

  cout << "the 0th argument is: " << argv[0] << endl;
  cout << "it first two chars are: " << argv[0][0] << " " << argv[0][1] << endl;

  cout << "all the other arguments were:" << endl;
  for(int i = 1; i < argc; ++i) 
    cout << argv[i] << endl;
  
  return 0;
};

argc is the number of arguments in the command-line (which includes the application's name).

argv is an array of C-strings (char*), the size of the array is argc. Each element in the array "argv" is a C-string. The zeroth being the name of the application itself, and the rest being each command-line argument (separated by spaces) (note that arguments between quotes "" will be put into one such C-string).

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

You are asking which language you should program in.. on a C++ forum! I think you know where this is going to lead.

C++ plays the central role in the world of computer programming. What that means is that all other languages define themselves in comparison to C++. It means most languages try to have a C++-like syntax to have the best chance of appealing to the massive body of C++ programmers, which means most other languages are easiest to learn when coming from a C++ background. It means also that most (if not all) platforms, operating systems, software tools, etc. are either natively in C++ or provide direct (or very good) compatibility/interface with it. Finally, it means that C++ is key in having broad competences in programming.

The above are (sort-of) facts, that might not mean that C++ is the best to start with. In my opinion, it is. But I'm a bit tough. People say that C++ has a steep learning curve (at least at first), and I would also say it's very long, but mostly because C++ is not limited to OOP, it has two more levels, i.e. generic programming and template meta-programming (that other languages don't have, or only partially).

The criticism you most often hear of C++ is that it is too close to hardware (too low-level), too complicated to port between platforms, and that memory management (or the lack thereof) in C++ is too error-prone. Yet, most companies that use C++ …

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

You should definitely use Boost.Thread. (you can download and install libboost-all-dev:

$ sudo apt-get install libboost-all-dev

Then, here are two simple examples. One with a global function and one with a member function.

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

Another problem you will have is that each compilation of those separate cpp files will have its own instances of "playerClass" and "warrior". This most probably not desirable. You could fix this with use of the "extern" keyword in front of those two global variable declaration, but I cannot, for the life of me, recommend that.

I highly suggest you make all your game functions as part of a game class (that handles the game):
gamefunctions.h:

#include "PlayerClass.h"
//using namespace std; //do not import namespaces in a header file!!


class Game {
  private:
    //PlayerList
    //Class,Health,Mana,Gold,Armor,BaseAttack,RangeOfAttack
    Player warrior;
    Player playerClass;

  public:
    Game() : warrior("Warrior",150,10,0,1,20,5), playerClass("",0,0,0,0,0,0) { }; 
  
    void hPlayer(int);
    //all your other functions ...
};

Then in gamefunctions.cpp (or in a few separate cpp files):

#include <iostream>
#include <iomanip>
#include "gamefunctions.h"

void Game::hPlayer(int PlayerC) // now a member function.
{ 
    //And the rest of the code remains essentially unchanged.
    switch (PlayerC) 
    {
        case 1:
            playerClass.setHitPoints(warrior.getHitPoints());
            break;
    }
}

And finally in main.cpp:

#include <cmath>
#include "gamefunctions.h"
using namespace std;

int main()
{
    srand(time(0));
    Game my_game;    //create an instance of the game!
    my_game.intro(); //and run it!
}

That ought to be much better than relying on global data. BTW, you can very often replace global data with an enclosing "super" class. With this, you will be one step closer to breaking the C-programming habits and becoming a C++ programmer!

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

If you look at the code of tutorial 1 for a real-valued problem, from the EO homepage. You see the very first function called "real_value". This calculates the fitness value for an individual. You can reprogram that function to do whatever you like. In your case, it should (somehow) give the set of coordinates (the vector of the individual) and hand it over to openWind, run the simulation and get the energy (or power) produced by each generator, sum it up and return that as the fitness value. If you cannot automate this process, don't even try to use a genetic algorithm for this project. GAs are based on massive trial-and-error approach with some breeding which makes it better than just trying things at random. But still, this requires a massive amount for simulation runs.. don't copy-paste individuals and enter the fitness after... this would be ridiculously time-consuming.

IMO, the EO side is easy.. I was able to find out how to do this in less than five minutes. What your biggest problem is, is how to run openWind simulation from the program (from within this "real_value" fitness function). It seems that openWind is an application, but it is open-source, so you can probably figure out how to make an API call to it to run a simulation and get the result (you might have to save the individual's data to a config file, then load and run openWind, and read the result file to calculate the …

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

I think I understand what you want to do, so let me put up a more consistent code and you tell me if that is what your question was about:

In Foo.h:

class Foo {
  private:
    int value;
  public:
    void PrintValue();
    void SetValue(int aValue);
};

In FooPrint.cpp:

#include "Foo.h"
#include <iostream>

void Foo::PrintValue() {
  std::cout << "Value is: " << value << std::endl;
};

In FooSet.cpp:

#include "Foo.h"

void Foo::SetValue(int aValue) {
  value = aValue;
};

And, finally, in main.cpp:

#include "Foo.h"

int main() {
  Foo f;
  f.SetValue(42);
  f.PrintValue();
  return 0;
};

The above scheme can be done (but is rather unusual) if the class (e.g. Foo) is very large (the implementation in a single cpp would be very large) or if there are some methods for which you would like to have a few alternative cpp files (e.g. FooPrintVersion1.cpp and FooPrintVersion2.cpp). This is totally fine (still unusual though) but OK.

If you want to compile this, assuming you are using gcc (or MinGW), you would have to do this command-line compilation:

g++ main.cpp FooPrint.cpp FooSet.cpp -Wall -o MyFooProgram

Or, if you have two versions of FooPrint, then you would have to different compilation commands, like so;

g++ main.cpp FooPrintVersion1.cpp FooSet.cpp -Wall -o MyFooProgramV1
g++ main.cpp FooPrintVersion2.cpp FooSet.cpp -Wall -o MyFooProgramV2

If you are using Visual Studio or another IDE of the sort, you would have to add all the cpp files that you have to the build (i.e. "Add source file …

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

Uhmm.. Maybe the problem is that both handlers that you have get executed at the same time (since they come in very quick succession. This could happen if the GUI handles events with multiple threads of execution. It registers an event for Mouse Enter, then starts to execute it, and during the execution, a Mouse Leave event is registered and starts executing before the other has finished. That possibly could cause a crash (but either your handler's execution must be slow or the GUI poorly responsive for that situation to happen).

Maybe you should add a critical section (or mutex) to prevent the execution of both handlers at the same time. By locking the same mutex or critical section in both handlers, you will force the second one to occur to wait for the first one to be finished, i.e. preventing them from executing simultaneously.

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

This is the basic singleton implementation. (I'm giving the link because, if you are going to look on the internet to find a copy-pastable implementation of it, you might find a poor one (like the one from AndySpb) and screw your code up with it, so at least, this link has a proper implementation (but only a very basic one, i.e. no thread-safety and no cross-modularity or ABI)).

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

I'm not sure, and I'm not so familiar with C++/CLI (which is not the same language as C++).

But what if you reach the line below, while a is still equal to -1. I think there is a slight chance that it does, so you might want to do a little check before that a is a valid index.

this->SquareID[a]->BackColor = System::Drawing::Color::DodgerBlue;
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>i lose the newly allocated space.
Exactly. If you set p = monster, you will lose access to the memory that was allocated before. But worse, you can no longer delete the memory you had allocated before (because you no longer have the address to it), this is called a memory leak!

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

I think you need to post the entire code, maybe you did something a little weird that upset the compiler. Otherwise, this shouldn't cause an error.

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

Yeah... your valgrind seems alright.

It definitely seems like its an OS problem of some sort. You might wanna use an older or newer kernel on your computer (like a RC version from a backport).

I'm not so familiar with architecture compatibilities, but have you noticed that the faulty build shows that your kernel is for i686 and you are building for target i486 (is that voluntary or could it be the cause of the problem).

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

And does Valgrind report any memory leaks, dangling pointers, etc.?

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

The original means:
Return a reference to the smallest of two variables from the caller's scope.

The first revision means:
Return a reference to the smallest of two temporary variables that will go out-of-scope as soon as the function returns. (i.e. This is an ERROR! This will lead to undefined behavior! You should not return a reference to a temporary variable (there are only very specific fringe cases in which this can be done/useful, but leave that to the experts)).

The second revision means:
Return the value of the smallest of two variables from the caller's scope.

A third revision (int min(int,int)) means:
Return the value of the smallest of two values passed to the function.

As for efficiency, well, they are fundamentally different functions, so it doesn't really compare. Between the second and third revisions (which accomplish exactly the same), the third one is a tiny bit more likely to be more efficient (avoids a level of indirection, in theory), however, in practice, it is almost certain that there will be no difference. The same goes for the original, which can be used in place of the second or third revisions (in theory it is slightly worse than the revisions, but in practice it's the same). But the original serves a purpose that no other version can serve, so, if that specific functionality is needed, it is the only option.

N.B.: the reason for this ordering of efficiency is only …

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

First, your statements:

delete [] KernelGaussian[0];

are not correct, you need to traverse the array of pointers and delete each one of them, as so:

for(int i=0;i<POINTS_VERY_FEW;++i)
  delete [] KernelGaussian[i];

Second, you should set all the pointers to NULL after you free them and check that they are not NULL before you free them. As so, for example:

if(KernelGaussian) {
  for(int i=0;i<POINTS_VERY_FEW;++i)
    delete [] KernelGaussian[i];
  delete[] KernelGaussian;
  KernelGaussian = NULL;
};

These changes should, at least, make your code a bit less error-prone. To be much less error-prone, I would suggest you use std::vector for all those arrays instead (this way you won't even need the Free function).

If that is not an option and you want to debug what you have, I would suggest you run it in ValGrind to really see what you are doing wrong with the memory management. From the code you have posted, I can't see the real source of the error. The value of PhiBins must have gotten corrupted somewhere else (maybe a simple typo like "if(PhiBins = NULL)" instead of the double equal sign).

BTW, you are missing the most important compilation flag in the command-lines you have posted, that is: "-Wall". If you didn't put it because it issued to many warnings, then that is very bad, enable it and take care of all the warnings. Then, debug!

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

If you are doing a lot of work with strings (I assume parsing), here are some general options to consider (from simplest to most powerful):

- stringstream (basic string operations, like an I/O stream)
- Boost.Regex (Regular expressions)
- Boost.Tokenizer (splitting strings into tokens and manipulating them)
- Boost.Spirit (LL Parser in EBNF grammars)
- Boost.Xpressive (recursive context-free grammars and expression templates)

If you have a more specific task (like parsing XML), then it is very likely that specific libraries exist in C++ that can do what you want.

Other than that, I don't really know how to use Python in C++ (I'm guessing you can just launch Python scripts, but that's very basic and not very nice).

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

To overcome the errors you should do a reinterpret_cast as so:

inFileDrs.read(reinterpret_cast<char*>(&(inTables[q].Items[j].Data[0])), inTables[q].Items[j].Size);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Read this. Then this (especially the note about sizes of integers in C++ which are dependent on the system you use).