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

Do as it says, use -> instead of .

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

If I may suggest another solution that you might find more elegant and that could serve other purposes for this class or another:

class MyTime {
   ...
  public:
    //create formatting containers:
    class MilitaryTime {
      const MyTime& obj;
      public:
        explicit MilitaryTime(const MyTtime& aObj) : obj(aObj) { };
        //implement ostream overload as you wish, using obj.
        friend ostream& operator <<(ostream&, const MilitaryTime&);
    };
    class MilitaryTimeNoColon {
      const MyTime& obj;
      public:
        explicit MilitaryTimeNoColon(const MyTtime& aObj) : obj(aObj) { };
        //implement ostream overload as you wish, using obj.
        friend ostream& operator <<(ostream&, const MilitaryTimeNoColon&);
    };
    //now, you can have a default format:
    friend ostream& operator <<(ostream&, const MyTime&);
    //and provide formatting constructor functions, if you wish (this is optional)
    MilitaryTime inMilitary() const { return MilitaryTime(*this); };
    MilitaryTimeNoColon inMilitaryNoColon() const { return MilitaryTimeNoColon(*this); };
   ...
};

int main() {
  //now say you have some time variable:
  MyTime current_time = ...;
  //you can print it in default format:
  cout << current_time << endl;
  //you can print it in military format, in either way:
  cout << current_time.inMilitary() << endl;
  cout << MyTime::MilitaryTime(current_time) << endl;
  //and the same for no-colon format:
  cout << current_time.inMilitaryNoColon() << endl;
  cout << MyTime::MilitaryTimeNoColon(current_time) << endl;
};

This kind of scheme is an easy way to get around having to create inheritance with multiple classes when the only functional difference between them is trivial (such as just an output format).

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

Just move this line 160:

LRESULT CALLBACK WinProc(HWND,UINT,WPARAM,LPARAM);//the real winproc

To the start of the code (after the includes) and all will be fine. The compiler has to know that there is a function (defined later) that is called WinProc and has the given prototype, before it gets to the line 50. Also, I'm pretty sure that you should take the address of the function as so:

cm_wcx.lpfnWndProc = &WinProc; //note the additional & before WinProc.
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I'm not an expert with this, but I have one idea / suggestion. This value of 4254684 looks a lot like a pointer value (converted to integer). Is it possible that you have a binary compatibility problem? Did you make sure that the static library in which the Array class template is instantiated into Array<double> is actually compiled with all the exact same compiler options? Maybe you can try to output via a member function (which is not as sensitive to binary compatibility problems) the value in integer form of the pointer array_. Just use a printf like you did for size() but for the pointer and compare that to the value that GDB outputs for the data member size_. I am suggesting that because it would explain why the function size() outputs the right value while GDB finds the wrong one. If binary compatibility is the issue, that behavior makes sense (GDB assumes a different binary footprint for the class and thus, looks at the wrong place for the value of size_, possibly where the pointer array_ is located in memory).

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

You have to link the proper libraries for any OpenGL application. Your prof should have given instructions on how to compile. I'm not sure, it has been a while, but I think you need to link with:
for Linux: libglut.a (add -lglut to the command line) and libopengl.a (-lopengl)
for windows: glut32.lib and opengl32.lib (in command line: -lglut32 -lopengl32)

You should browse the web for instructions for your OS on linking to the GLUT libraries and OpenGL (probably only GLUT is needed). And, of course, you need to have GLUT installed on your system too!

hope this helped a bit.

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

The idea with the WinProc function is that the first parameter "hwnd" is the handle of the window whose message belongs to. So what you need to do is have a simple conditional inside the WinProc to redirect the message handling depending if the hwnd is for the first or second window.

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

All these extra threads are there because a GUI is built with several elements that are supposed to appear as running simultaneously. So it is not uncommon to see a GUI having tons of threads running. The underlying mechanisms of many GUI elements involve passing windows messages between semi-sleeping threads. That's why, for example, some applications, when they freeze because of some intense computation on the main thread, will have some items on the windows that seem to still work (display is updated correctly, when you click a button it pushes down, etc.) that indicates how some components are built to run on their own thread. In fact real-time operation and semi-simultaneousness were the main purpose of multi-threading, and still is now even with multi-core computers (where the concept of parallel computing is much more relevant in increasing performance).

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

>>but it actually is clearing the 4th element. How could it work here???

It deletes the 4th element because the begin() points to the first element, so, begin() + 3 points to the fourth element. That makes total sense, doesn't it? And vector.erase will erase the element that is pointed to by the iterator you give it. So that's all there is to it, it makes perfect sense.

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

First of all, after entering a single character, you usually want to call the ignore() function on cin to ignore the rest of the characters in the interval ]first character .. new-line (or enter)] (note the exclusive and inclusive brackets).

Now, if you want a single character input in the console. That is not standard, so, as far as I have seen, this is not possible with any standard function (see the thread on flushing the input buffer). In windows, you can use the header <conio.h> which has this lower-level function called getch() which can get a char directly as it is being typed (with or without echo to the console). If you are in Linux, then the library for it is curses.

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

At line 65, 66, and 67, you should have (index) instead of (index - 1). In the case you have index == 0, that would result in -1 and delete the element before the first one, which should result in the error you have got.

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

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

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

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

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

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

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

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

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

#include <cstdio>

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

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

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

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

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

#include <cstdio>

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

If all you want is an easy solution, here is the easiest of all:

#include <cstdlib>
int main() {
  system("octave");
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

indexing in C++ goes from 0 to N-1, so your code should be (in code tags) as:

#include<iostream>

using namespace std;
int main() //main always returns an int value.
{

  int pro[100];
  for(int a=99;a>=0;a--)
  {
    pro[a]=a+1;
    cout<<pro[a]<<"\t";
  }
  return 0;
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It was crashing while closing the file probably because writing on the memory after that single char that was allocated probably spilled over to the memory of the ifstream object and corrupted it. Thus, when closing, it would use its corrupted information and cause a segmentation fault.

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

Ho, it took me a while to find this one.. here is your erroneous line 63:

char *buffer=new char(length+1); //these parenthesis should be square brackets.
//like this:
char *buffer=new char[length+1];

The effect of the normal parenthesis is to allocate space for only one character and initialize its value to length+1.

You should also call delete[] on this pointer before exiting the function.

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

@firstPerson: Your right! I was confused with partial template specialization. The problem was never about calling the function and getting to compiler to instantiate the function template, but about the specialization of the template based solely on the return type. From one of Kanoisa's posts, it seems his compiler did not allow for specialization of the function template if only the return type was templated. But the C++ standard (and thus a standard compiler like gcc), will allow total specialization of a function template based on a templated return type, but it will not allow a partial specialization of a function template like:

//generic function template prototype:
template<class T, class U>
T foo(U);
//Illegal partial specialization:
template<class U>
int foo(U) { .. };

But your right, in this context, it appears it works fine as you showed. I was wrong to generalize the rule of illegal partial specializations by return type to total specialization by return type only.

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

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

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

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

You guys have looked over the main point here. You cannot do a template specialization of a function for only a templated return type. That's why Kanoisa had to put a dummy parameter to the function, otherwise the compiler will not allow the specialization and say, in this case, "explicit specialization ... is not a specialization of a function template".

As you did Kanoisa is OK. If you want to avoid the overhead of passing a variable of type T to the function, you can use the type2type idiom for the dummy parameter, as so (taken from Modern C++ Design by Alexandrescu):

template <class T>
struct Type2Type { //create a dummy template class that occupies no memory.
  typedef T OriginalType;
};

template< class T >
T qAndA(const std::string Question, Type2Type<T>)
{
	T answer;
	std::cout<<Question<<std::endl; //ask the question
	std::cin>>answer; //get the response
	std::cout<<"returning a "<<typeid(T).name()<<std::endl;
	return answer;
}
template<>
std::string qAndA(const std::string Question, Type2Type<std::string>)
{
	std::cout<<Question<<std::endl; //ask the question
	std::string answer;
	getline(std::cin, answer);
	std::cout<<"returning a string"<<std::endl;
	return answer;
}

using namespace std;
int main(int argc, char* argv[])
{
	string meh;
	meh = qAndA("What! is your quest?: ",Type2Type<string>());
	cout<<"you entered "<<meh<<endl;
	cin.ignore(1000,'\n');

	int x = 0;
	x = qAndA("What is your favourite Number",Type2Type<int>());
    cout<<"you entered "<<x<<endl;
	cin.ignore(1000,'\n');

	char ch = 0;
	ch = qAndA("What is your favourite Letter",Type2Type<char>());
	cout<<"you entered "<<ch<<endl;
	cin.ignore(1000,'\n');

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

the header is <iomanip>, see top right corner of this page.

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

Try and check if the SetCommMask is return true or false. And use GetLastError to see the error message, that's all I can think of.

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

The output of the first piece of code is 14 because the value of variable ival (referred to by ref) is set to the value of ival2 (which is 14). A reference can only be set once, upon construction (line 4). Afterwards, any operation on the reference is exactly as if it was the variable it refers to. It is essentially like as if you just change the name of the variable. If you print out the value of ival too on line 6, you would also get 14.

>>1 more thing- do references occupy seperate spaces in memory like pointers ?
That depends on the case. In the example you posted, no, because the compiler is intelligent enough to know that ref is ival and there is no point in creating a "pointer" to ival (sort of encapsulated in the underlying implementation of the reference type). But under other circumstances (like getting a variable passed by reference to a function) it is more likely that the compiler will implement the reference with an underlying "pointer", but that depends how complex (inline or not, and the memory pattern on the stack) the situation is and how clever your compiler is.

For the second code snippet, I wasn't sure myself what a sizeof on a reference would output. So to feed my curiosity I tested this:

char ival = 12;
  char& ref = ival;
  std::cout << sizeof(int&) << " " << sizeof(ref) << " " << sizeof(ival) …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

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

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

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

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

The reason for this to happen is that the compiler generates a default = operator for any class that doesn't provide one. So, in this case, the compiler generates a = operator for A<double> = A<double> that has a better match than the A<double> = A<X>. So you would have to implement the non-template operator =(const A<T>& a) too.

I don't know a trick to get it to work without that second operator definition. Maybe template specialization of the operator will work, but would effectively be the same (still have two implementations of the operator).

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

>>She got you. You should at least admit it.
Well I thought I did! If it wasn't clear, let me say it clearly: You are right Narue and I was wrong. Thank you for increasing my understanding of C++ vocabulary and adding this little trick to my bag-a-tricks.

I thought that "In my view, I'm still right" clearly said that, but maybe I still got something to learn about the English language. So, alternatively:
"De mon point de vue, je n'avais pas tord"
"I min egen uppfattning, hade jag rätt"
"Im meine eigene verständigung, hatte ich recht"
"Minun näkökulmastani, en ole väärässä"

PS: who did you think up-voted Narue's post? (rhetorical)

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

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

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

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

John Sand commented: Great advice on C++ programming. +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>So you guys would recommend using SQL queries?
NO, I was just mentioning this because it is part of what IT people call a database.

I would recommend using the Boost Serialization library if you want to be trouble-free. But this uses template code a lot, so it might be hard to use if you are not proficient with that.

If all you want is save/load data structures to a file(s). First, you need to choose whether you want a binary or ascii file, i.e. computer-readable or human-readable, respectively. Then you need to know if you need a lot of classes and structs to be saved and loaded, or if it is just one type of data (a list of small data structures). Finally, you need to determine if you have an object graph to save/load (an object graph being a set of objects that use each other via pointers or references).

The Boost Serialization library is geared for the most complicated case (both binary and ascii, large object graph with many heterogeneous types). But it can also easily serve the simplest case (binary, one type of data structure, no object graph). I have my own serialization library that pretty much does the same as the Boost one (but a bit differently), for both binary and XML.

Basically, the way you had it in the original post is quite alright for the basic case. You might want to think and make sure the …

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

From what you have posted, it doesn't really seem like you are really making what most people call a DataBase (which generally uses a database server using some SQL queries and such. Examples include MySQL, Oracle, etc.).

In your case, this is what most programmers would call a memory serializer. Anyhow, when saving to a file, you have to consider how easy it is to save, how easy it is to load (or parse) the file, and how much complex the objects can be. Generally, the XML syntax is quite good and there are several open-source libraries for loading and saving XML files (or you can do like I do, which is to make your own library, because the XML format is very simple but also very flexible).

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

@Narue:
Well I guess we have different nomenclature, I consider a function as pure virtual (or abstract, as a remnant of my Delphi days) only if there is: 1) "= 0;" at the declaration and 2) no implementation anywhere (if you put it next to the derived class definition or anywhere else doesn't make a difference to me, it is no longer a pure virtual method or destructor). So in my view, I'm still right ;) it does make sense for a destructor to have either no definition or no compiler-generated default definition.

But you have an interesting point about using a "semi-pure" virtual destructor in a base class to force its derivation. I didn't know that trick and I'm glad I learned it. Thanks.

PS: your right about the compilation error, I didn't try on my compiler, I just got that info from a quick google search and all the links said the same thing so I figured it was true.

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

I usually tackle these problems by looking at the boundaries. In your case, you have the basic scaling factor is "energy / max" which is at most 1 and at least 0. So in any logarithmic scale (I would assume you want base 10, but that doesn't really matter), these bounds translate to at most 0 (log(1)) and at least -infinity (log(0)). So you have a bit of a problem, you see. You will have to do a bit more work to get anything sensible out of that.

So, say you have base 10, the desired output, normally, is that if the energy of one object is ten times that of another, it should be one unit bigger. Really the only way I can think of is to set some minimum value of energy. Say the minimum for "energy / max" is 10^-10, which, in log10, is -10. Then a scale function like this might work:

//this checks the lower-bound, if greater then use log10 + 10 (offset), if lesser then use 0.
double logScaleFactor = (energy > 1E-10 * max ? log10(energy / max) + 10 : 0);
..
corners[i].x = centre[0] + ( corners[i].x - centre[0] ) * logScaleFactor; //now, the scale factor will be between 0 and 10.
corners[i].y = centre[1] + ( corners[i].y - centre[1] ) * logScaleFactor;
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If I may add a few things to the already good answers from Narue and Fbody.

First, although Narue showed a case where explicitly calling a destructor, it's important to say that there is virtually no other reason where an explicit call to the destructor makes sense and the placement new are very rarely used and not recommended in general. Because most of the time, objects will be created either dynamically (with new or new[]) or as a scoped object (local variable), and in both of these cases, calling the destructor explicitly is VERY error-prone (basically any non-trivial destructor will cause a crash when it is implicitly called again).

Second, it is important to know the behavior of the following code, because many beginner programmers might be tempted to do that (in a less trivial case):

class Foo {
    int a;
    double b;
  public:
    Foo(int A, double B) : a(A), b(B) { }; //Parametrized constructor.
    Foo() //default constructor
    {
      //might be tempted to do this (in a less trivial class of course).
      Foo(0,0.0); //calling the other constructor explicitly. BIG MISTAKE!
    };
    //In this trivial case, the following constructor would make more sense:
    Foo(int A = 0, double B = 0.0) : a(A), b(B) { };
};

One might expect that the above calls the parametrized constructor on the "this" pointer that is relevant to the default constructor, i.e. that this will actually initialize the values of a and b to default values 0 and 0.0. But in …

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

NO, at least, it would be extremely surprising and weird. Just try and see. I bet you that if you have a proper compiler, it will issue a compilation error.

Why? Well it does not make any sense to have a pure virtual destructor. Because virtual destructors are not like normal virtual functions, they don't get overridden, they get extended in the derived classes. This is because each base class is responsible for cleaning up it's own data members (if they hold dynamically allocated memory or other resources like sockets or threads). When the class is derived, the author of the derived class should not be given the responsibility of reimplementing the destructor of the base class (what if he doesn't know how?). So, instead, the C++ standard prescribes that the destructors be called essentially in an upward order, i.e. from most derived to most basic class. This is true whether the destructor is virtual or not. The reason for virtual destructors is to make sure that, at run-time, the destructor of the most derived class is called first (via dynamic binding) and then that destructor will relay the destructor call to its base class(es). The ordering goes the other way for the constructor, i.e. the most basic class first then downwards to the most derived class constructor. The only exception is multiple virtual inheritance in which the order is a bit different.

Since you can only have one destructor (no parameter and no return type, so, no …

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

When I look at this code, I remember why people don't program in C so much any more... This post probably belongs in the C programming forum instead.

Anyhow, there is one definite problematic line, that is line 28. I found it, because that's always the first thing I look at when looking for a bug: where / how is memory allocated, where / when / how is the memory freed, where / how is it used, then is the algorithm sound. (in that order of priority!). So, the error is that you allocate the space for one struct object of type List_t, then assign the resulting pointer to a pointer-to-pointer to type List_t, and then fill it up in a for-loop with bound "size". So my awesome power of deduction tells me you intended that line 28 to be:

NewTable->table = (List_t**) malloc( size * sizeof( List_t* ) );

That should help, for the rest, it's harder to tell where the problems might be, try going through that same order of priority in checking your code.

BTW, why do you double each function definition? It's the first time I see that and it looks horrible! And it is completely useless. There is no point in putting the prototype of the function right before its definition. A prototype announces the existence of a function before it is defined, to the code that follows. But if, immediately after, you have the definition itself, the prototype is completely meaningless.

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

Hardware programming on a PC is essentially I/O programming. This means you program drivers that communicate with hardware using some channel or port. So there is no general books about it. It's all about knowing the ports you work with, the OS calls necessary to open, configure and use the ports, the specifics of the communication protocol used across the port, and the hardware vendor's spec-sheet on the commands and packet formats.

Hardware programming takes a lot of patience because there is hardly any simple ready-to-use solution or textbook examples. It's case-by-case. Every hardware is different and you often have to go through thousands of pages of spec-sheets, command specifications, user manuals, programming manuals, etc.

If you tell me what is the port you work with, what communication protocol is used, what platform you are running on, and what hardware circuit you are interfacing with, then maybe I can help.

Finally, if by "we programme hardware using C++" you mean that you are programming stuff on a micro-controller or micro-PC, then there are certainly more resources for you. Generally, most people use either AVR Studio or Arduino for programming on micro-controllers (AVR Studio for example can simulate the hardware IO signals and the actual operation of the micro-controller). But, generally, you will find mostly C programming, unless there is a OS running (like Micro-Linux, Embedded Windows, FreeRTOS, etc.) then there are possibilities for cross-compiling C++ code (MicroLinux is especially nice and easy).

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

First of all, your file is in binary, because all data is binary on a computer.

Second, you use the sizeof operator incorrectly. sizeof gives you the size of the type at compile-time. In this case the type of buf is a pointer to char which, most likely, has either 4 or 8 bytes. So sizeof(buf) will equal either 4 or 8. So what you will get in the file output is either "Bina" or "BinaryFi".

So, to get the actual length of the string pointed to by buf, use the function strlen(buf).

Now, to the meat of it. What is "BinaryFile"?

In ascii characters notation (null-terminated string):
'B' 'i' 'n' 'a' 'r' 'y' 'F' 'i' 'l' 'e' '\0'
In decimal numbers notation:
 66 105 110  97 114 121  70 105 108 101   0
In hexadecimal numbers notation:
 42  69  6E  61  72  79  46  69  6C  65  00
In binary numbers:
 0100 0010 0110 1001 0110 1110 0110 0001 0111 0010 0111 1001 0100 0110 0110 1001 0110 1100 0110 0101 0000 0000

Now, the point is this: All of the above are exactly the same! A text editor, like notepad, loads the binary data (i.e. computer memory) and show the ascii character representation. While so-called hex editors, will load the binary data and show the hexadecimal number representation.

Whether you have intelligible text (like in your example) or raw data (like saving an integer or float, or any thing besides a string), they …

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

As suggested by firsPerson, you need to add a seed for rand (srand) and closing the file is useless (it will be automatic when the program finishes and outfile is deleted). So, try this (and indent better in the future!):

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
       
int main(){
  ofstream outfile("C:\\Random.txt"); //Random as in you can put any file you want
  srand(time(0));
  for(int i = 0; i != 10; ++i){
    outfile<< rand() << endl;
  };
  return(0);
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you are just starting out, it is a bit of a jump to be writing vertex buffers. Don't you think? Try going through the NEHE tutorials in order (they are quick and easy to follow, and before you know it you'll be rendering flags flopping in the wind on top of a hill with a bunch of trees around and a beach!).

Anyhow, if you want to make it look more 3D, the perspective you have there is fine (normal camera perspective transformation, the usual). What really make your cube look 2D is because you are looking at it directly in the face, so it will just look like a square not a cube. Try adding glRotatef() after glTranslatef(), play with the parameters for a while and you should see more of a 3D cube.

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

NicAx has a good point, just to add my thought: If that DLL is, as you say, tehmarto, in an encrypted resource-file in the game-data folder (and that is why you can't just do a file search for it). There is at least a chance that the game extracts the DLL to a temporary (hidden) location and then loads it from there. In that case, that program NicAx suggested might be able to find that temporary DLL while the game is running (or at least while it is loading up, because they might just delete the temporary file after loading it).

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

>>But I am writing data into a MIDI file, hence...

Well, then it is option two in my last post. MIDI is a binary file. So hex are used extensively for inspecting the content manually and understanding its binary format because it is the representation that is the most convenient for that. But you have to understand that there is a BIG difference between the string value "10" and the hexadecimal value "10" (or 0x10 in C/C++ syntax). The best way to see is to look at the binary data (what is actually saved in the memory, i.e. 0s and 1s):

"10" is equal to hex: 0x313000, and binary: 0011 0001 0011 0000 0000 0000
0x10 is equal to binary: 0001 0000
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

wow, I think you have a couple of concepts mixed-up here.

Hexadecimal numbers are just a notation for numbers in base 16 (like decimal is in base 10, binary in base 2, and octal in base 8). The computer stores only binary data, so any value is represented in binary. One special case is character representations (typically type "char" in C/C++). A char is still a binary number of 1 byte (0 to 255 value (unsigned), or 0x00 to 0xFF value (in hex)) which translates, through the ascii table, to a character that can be displayed.

The only reason why hex is used is because you can represent 1 byte with no more than 2 digits (16*16 = 256). So that is why a program like okteta and others are used to read binary data by showing there hex values (each pair of digits representing one byte) as opposed to a text editor (like notepad or emacs) that would translate the binary data with the ascii table into senseless characters. Because a binary file and its bytes were never meant to represent anything directly intelligible to a human being, but in the natural language of the computer instead (this is faster, smaller and more robust if there is no need for a human to inspect the file directly).

I'm saying all this because your question doesn't make much sense.

First of all, the decimal number 16 is 0x10 in hexadecimal notation not 0x0A (that is 10).

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

Your problem is that you declare the array of vertices as having 9 coordinates in total, which would only include the first 3 points, i.e. the first triangle.

//This is where that is set:
 glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 9, &vertex[0], GL_STATIC_DRAW);

//This is what it should be:
 glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 24, &vertex[0], GL_STATIC_DRAW);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@wft4096: You gave a very interesting suggestion, openMP seems very nice. However, relating to the OP's question, Multi-threading and Parallel computing are two different things. The former is for flexibility and (real-time) multi-tasking, while the latter is for increasing performance of large scale algorithms on multi-core processors or super-computers or other parallel / distributed platforms of the like.

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

Try going through these instructions for building the libraries on windows.

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

Well, okteta reads binary data and prints it out in hex format (to be more readable than if you opened a binary file in a text editor). So what you need to write is binary data:

ofstream myfile;
myfile.open ("output.midi",ios::binary);
char buffer[44] = {0x4D,0x54,0x68,0x64,0x00,0x00,0x00,0x06,0x00,0x01,0x00,0x01,0x00,0x80,0x4D,0x54,0x72,0x6B,0x00,0x00,0x00,0x16,0x80,0x00,0x90,0x3C,0x60,0x81,0x00,0x3E,0x60,0x81,0x00,0x40,0x60,0x81,0x00,0xB0,0x7B,0x00,0x00,0xFF,0x2F,0x00};
myfile.write(buffer,44);
myfile.close();
dorien commented: His post totally helped me out! +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, you can use the std::sort algorithm in "#include <algorithm>". The only little problem is that it cannot be used with a list because list provides only bidirectional iterators, not random access iterators, which is required for the sort algorithm.

So you need to use a vector instead. Also, the compare function has to taken parameters of your struct type. So simply put:

#include <vector>
#include <algorithm>
using namespace std;

struct myStruct {
  int i;
  string s;
};

bool compare(const myStruct& first, const myStruct& second)
{
  if (first.i < second.i)
    return true;
  else
    return false;
}

int main()
{
  vector<myStruct> myList;
  
  /* Pretend that myList has elements with values */
  sort(myList.begin(),myList.end(),compare); //that's it! 

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

I will advocate for Boost again... Boost has this Date-Time library which implements a microseconds clock (even a nanoseconds clock). It will run on any "normal" operating system. Of course, it will only really be as precise as your system can provide, but it will output the results in microseconds anyway.

Here is a very basic example:

#include <boost/date_time.hpp>
#include <iostream>
using namespace std;
using namespace boost::posix_time;

void runFunctionHere(){}

int main(){
  ptime start = microsec_clock::local_time(); 
      runFunctionHere();
  ptime end = microsec_clock::local_time();
  cout << "Time took in microseconds : " << (end - start).total_microseconds() << endl;
}

Here is the profiler class I use (feel free to use it):

#include <vector>
#include <fstream>
#include <ios>

#include <boost/date_time.hpp>

class exec_time_profiler {
  private:
    std::vector< boost::posix_time::ptime > mTimeTable;
    std::vector< int > mIDTable;
    
    std::ofstream mOutputStream;
    
    uint mCurrentIndex;
    uint mTotalCount;
    
  public:
    
    exec_time_profiler(const std::string& aFileName) : mTimeTable(),
                                                       mIDTable(),
                                                       mOutputStream(aFileName.c_str(),std::ios_base::out | std::ios_base::trunc),
                                                       mCurrentIndex(0),
                                                       mTotalCount(0) { };
    ~exec_time_profiler() { mOutputStream.flush(); };
    
    void markTime(int Index) {
      if(mTotalCount > 0) {
        if(mCurrentIndex < mTotalCount)
          mTimeTable[mCurrentIndex] = boost::posix_time::microsec_clock::local_time();
      } else {
        mTimeTable.push_back(boost::posix_time::microsec_clock::local_time());
        mIDTable.push_back(Index);
      };
      mCurrentIndex++;
    };
    
    void flush() {
      if(mTotalCount == 0) {
        mTotalCount = mTimeTable.size();
        for(uint i=0;i<mTotalCount-1;++i)
          mOutputStream << mIDTable[i] << " to " << mIDTable[i+1] << "\t";
      };
      mCurrentIndex = 0;
      mOutputStream << std::endl;
      for(uint i=0;i<mTotalCount-1;++i) {
        boost::posix_time::time_duration delta_t = mTimeTable[i+1] - mTimeTable[i];
        mOutputStream << delta_t.total_microseconds() << "\t";
      };
      mOutputStream.flush();
    };

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

POSIX is essentially for Linux or Unix systems. POSIX is just a specification for the API that the OS needs to expose and Linux, Unix and many others comply to those specifications. Windows does not, so windows has its own things, for example, via its Win32 API.

Boost Thread library is cross-platform in the sense that it's implemented to work with POSIX and Win32 (maybe others too, I don't know). In the coming C++0x standard, all operating systems will be required to implement a common multithreading library (std::thread), which will be almost identical to Boost Thread, because virtually all the new C++ standard libraries come from Boost.

So, I can give you a simple example, working with Boost Thread. First of all, the thread functions are in the form of function objects (or function pointers, but that's not very nice to use). A function object for a thread has to have a () operator. So here is a simple example that prints the number of times a thread loop has executed, with a "quit" option:

#include <boost/thread/thread.hpp>
#include <iostream>

//function object class that will be used to run the thread.
struct PrintThreadLoopCount {
  bool* Running; //declare a flag to tell whether the thread should still be running.
  int LoopCount; //count the amount of times the loop has run.

  //constructor
  PrintThreadLoopCount(bool* aRunning) : Running(aRunning), LoopCount(0) { };
  //copy-constructor (required if default is not good enough)
  PrintThreadLoopCount(const PrintThreadLoopCount& aObj) : Running(aObj.Running), LoopCount(aObj.LoopCount) { };

  //Declare a () operator method …
Ancient Dragon commented: Always posting such great stuff :) +33
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

4) Use are reference of the Parent type to call the overload:

#include <iostream>

class Parent
{
  public:
    virtual int Add(int a, int b) = 0;

    int Add(int a)
    {
      return this->Add(a,a);
    }
};

class Child1 : public Parent
{
  public:

    int Add(int a, int b)
    {
      return a+b;
    }
};

int main()
{

  Child1 test1;
  Parent& ref = test1;
  std::cout << ref.Add(3) << std::endl;

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

In general it looks quite alright. Of course, I assume there will be future iterations on that problem in your book, because the instructions stated at the beginning will certainly be changed later to a more clever design. But I don't want to spoil it for you.

One mistake that is very important here is that you don't need to pass the vectors Names and Ages to all the functions you have. Since Sort and Print are member functions (called methods) they have access to the data inside the object of type Name_Age, so they can access the vectors Names and Ages directly without having to pass them as parameters.

Another improvement is to realize that those variables name, name2, age and age2 are used only locally inside the methods (to read in the values from cin). So you don't need those a data members, simply have them as temporary local variables inside the methods.


So a simple improvement on your code will result in this:

/*
This program solves an exercise.  The requirement is to first create a class holding a vector of names of individuals and a vector 
of their ages as members.  Then write a function that reads the names into the vector, a function that reads their ages into the 
vector, a function that sorts the names alphabetically and also sorts the ages to remain matched to the names, and finally a 
function that prints out the sorted names and …