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

If wealth is supposed to trickle down, 99% percent of the people must be standing under a giant waterproof cover.
Plethora

codeorder commented: .spot on. :) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

vacuum -> chamber

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

Just run the client and the server on the same computer. You run the two programs separately.

Assuming you're connected to the internet, then you have an IP address. If you send packets from your computer to your own IP address, then it's gonna work, the packets will simply go to your router / access-point and right back to your computer. The client can send a packet to its own IP address, which comes right back and is picked up by the server. You can get a few conflicts between the client and server if they are listening to the same address and port all the time, so you should use different ports for outgoing and incoming communications (e.g. the server listens on port 4302 and sends on port 4303, and vice versa for the client... you get the idea).

If you can't connect to the internet or a local network of any kind or simply want a faster connection, then use a loopback. This is a virtual device that acts as a network "echo". As in, whatever you send to it, it will give it back to you. This is actually one common way to communicate between programs running on the same computer. On Windows you follow these instructions to enable loopback. Under Unix/Linux, it's always on (or at least, by default) at address 127.0.0.1 as usual.

You really don't need to look very far for this info, the example of MSDN for winsock is …

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

So then, how do games like Call of Duty do it? Clearly they are able to set up a server (host) and clients.

Ever heard of Service Discovery Protocols (SDP), and other systems like Zeroconf and UPnP.

When nezachem suggested that you put the discovery part aside for now, this is not to mean that it is impossible (and games like Call of Duty certainly have a solution to this, either their own or using one of many standard protocols to do this). It's just that the discovery part is a bit harder to do correctly. So, if you are having trouble just making simple socket communications, I also suggest you start by getting that to work (manually starting and configuring the server/client, and then concentrating on getting the back-and-forth communication working), then you can work on a solution for the automatic discovery and establishment of connections.

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

Well, the problem statement specifies that n <= 10^9, which makes it fall in the 32bit range. So, my solution works for the problem that was given. However, your solution is really cool! But it has a few mistakes, this version is more accurate:

unsigned int get_highest_power_of_2(unsigned int N) {
  unsigned int bit_padding;
  for(unsigned int shift = 1; ((shift < 8 * sizeof(N)) && (bit_padding = N >> shift)); shift <<= 1)
    N |= bit_padding;
  return N & ~(N >> 1);
};

I fixed the 8 * sizeof(N) which I guess you simply forgot. And I made the loop stop as soon as there are no more bits to pad.

And of course, I agree, most of the execution time of the actual program is the capturing and printing of the 10^6 test cases.

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

As deceptikon says, it can be done, and probably more easily through function overloading (a free function taking the ObjectHolder and the ClassName and type), because then you can overload based on the class type and change the return type accordingly, which is harder to do as member functions.

However, there really isn't any point to doing this. If you consider this expression:

MyClass* ptr = objectHolder->getObject <MyClass> ("MyClassname");

or:

auto ptr = objectHolder->getObject <MyClass> ("MyClassname");

It is very terse and clear already. You can almost read it from left to right as a normal sentence: "Ask objectHolder to get an object of type MyClass with name "MyClassname"". How clearer do you need it to be? Although you could do it your way, it would be a bit hard (under-the-hood), it would probably not be as nice as you'd like (probably would result in:

auto ptr = getObject(objectHolder, "MyClassname", (MyClass*)(NULL));

, and you would be breaking the conventions of C++, that is, type-parameters are as template arguments and value-parameters are as function parameters, trying to flip that around is useless, unclear, difficult and weird for everybody else.

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

The logic is that the preferred position is the highest power of 2 that fits entirely inside N. The process is like this, at every round, the first element will be taken out and the second element will be left along with every two element following it. After the last selection round, there will be only one number left (the preferred position if you want to be selected), which is also the first number in the set (a set of size 1). At the start, the first number is 1, then it is 2, then 4, then 8, then 16, and so on... until you hit a number whose double is too big for the original list, that means that that number is the one selected. So, you can skip all this brute force stuff and just compute the largest power of 2 that fits in N. And because integers are represented with bits, you can just find the highest bit that is set to 1 in the number N. So, the Power2(Log2(N)) essentially finds the position of the highest 1-bit and finds the number it corresponds to. FirstPerson's code does the same (albeit more tightly packed).

Neither firstPerson nor VernonDozier solve the problem in the fastest way, here is the fastest way:

#include <cstdio>

int main()
{
    std::size_t T = 0;

    std::scanf("%i",&T);
    std::size_t *ansArray = new std::size_t[T];

    for(int i = 0; i < T; ++i)
    {       
        unsigned long maxApp = 0;

        std::scanf("%ul",&maxApp);

        // Find the highest power-of-two number in …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is not gonna be a problem. When you call a member function of a class, it is called on the object pointed to by the "this" pointer. So, the this->id is the vector within that object, so it will be modified directly (without a copy).

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

To add to Tumlee's comments, I would suggest your prototype for the printPayroll function should be like this:

void printPayroll ( const vector<Records>& v );

Use the passing by const-reference to avoid copying such a large object as a vector.

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

Wanna bet??? ;-)

I was just listening to Herb Sutter's C++11 presentation for GoingNative 2012 where he argues that there isn't really much reason for the new operator to even appear in modern C++ code (and certainly not delete, which I haven't used in ages), let alone malloc/calloc/realloc. Considering that with the new standard, individual heap-based objects should be created into a smart-pointer directly (with make_shared or other forwarding factory functions, hiding the new call), that move-semantics makes passing-by-value much cheaper (reducing the need for heap-based objects), and that containers are made more flexible and powerful, all this makes for a modern C++ world in which new/delete is seldom needed (at least in higher-level code). But if you include low-level or library code, then of course you will find uses of malloc and other low-level memory functions. How do you think std::allocator is implemented? But this is arguably not really the kind of C++ code that most people would ever write (in other languages like Python, all the library code is in C or C++, so it is not Python. But in C++, the library code just happens to be in C++, but you could argue that this code is not really C++, if you get what I mean..). Today (not in legacy code), you should only find new/delete or malloc/free calls in the guts of some library code (standard or custom-made), but not in user-side code, and thus, if you write a library, you should design it …

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

In reality, you could probably use some clever bit-wise tricks and some low-level instructions to quickly extract this kind of information (which is probably what library code does). But that's too complicated to do in an exercise question.

Assuming you will not go as far as outputting the result in a "smart" format (like scientific notation when appropriate and so on) and that you are only printing numbers reasonably close to 0 (between 10^6 and 10^-6 or so), then you can simply use an algorithm roughly like this. First, you can have an algorithm to print an integer value:

  • Find the lowest power N of 10 that is greater than you number (M).
  • Then, for each power of ten, call it i, between 10^N and 1:

    • print the character corresponding to the integer division M / i
    • subtract the higher digit from the number, as so: M = M - i * (M / i);.

Now that you have an algorithm to print an integer, printing a double value is simply a matter of splitting it into the "integer" value that comes before the decimal place and the "integer" value that comes after. Here is a simple way to do that:

int get_before_decimal_pt(double value) {
  if( value >= 0.0 )
    return int(std::floor(value));
  else
    return int(std::ceil(value));
};

int get_after_decimal_pt(double value, int number_of_digits) {
  value = value - get_before_decimal_pt(value);
  return int(std::fabs(value) * std::pow(10,number_of_digits));
};

Then, you get two integers which you can print. First, you print the before-decimal-point …

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

Correction on Banfa's last post. You cannot make the assignment operator into a free function, it must be a class member function. So, Banfa's code will not work, although he is very correct in suggesting the free function operator overloading instead of as class member functions, this is generally preferrable (for the operators that are allowed to be overloaded as free functions).

I have a problem with your use of the assignment operator for push-pop operations. The problem is that you shouldn't drastically change the semantics of an operator when creating an overloaded version of it. All programmers generally see the assignment operation as exactly that, an assignment of the contents of the right-hand-side to the variable on the left-hand-side. Overloading it to mean pushing a value on the left-hand-side stack is a bad and confusing idea.

If you absolutely need to use a set of operators for push-pop (btw, what's the problem with just having a "push" and "pop" function?), then you should use the << and >> operators instead (with semantics and chaining behaviour that mimics the iostreams). And those are allowed to be free functions, so you can do this:

Stack& operator<<(Stack& left, float right) {
  left.push(right);
  return left;
};

Stack& operator>>(Stack& left, float& right) {
  right = left.pop();
  return left;
};

This will allow you to create code like this:

int main() {
  float values[] = {0.0,1.0,2.0,3.0};
  for(int i = 0; i < 4; ++i)
    std::cout << values[i] << " ";
  std::cout << std::endl;

  // …
Banfa commented: Doh, thanks for catching my mistake +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The easiest would probably be to reinstall backtrack linux, and merge the partitions as part of the install process. You can always backup the home folder (or others) and any other system files (which you can later resynchronize with rsync, or manually with diff on all the config files). And if you don't want to lose the list of packages that you installed, just get the list with dpkg -l, save that to a file and after the fresh install you just feed that list to apt-get. I did that process with a ubuntu -> kubuntu migration, and it didn't take more than an hour total.

But if you really can't do a fresh install, then it's a bit harder and more time consuming, but possible.

I'm not sure if GParted or other similar partition managers (or fdisk) are able to take the deleted the windows partition(s) and extend the main linux partition with that (assuming the physical layout of the partitions will permit it). If it is possible, then you can just do that.

It is possible that your boot-loader will be confused by this change and no longer be able to boot you linux install (are you dual-booting by chainloading grub with neogrub, or by using grub on the MBR?). So, I recommend that you have a suitable LiveCD ready in case you have to repair the bootloader (and, btw, if you're doing information security stuff, you probably want to use a LiveCD all the time anyways, or …

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

An API (Application Programming Interface) refers to a set of specifications on how you can make function calls to a library to perform certain operations (basically, a specification, from a programmer's point-of-view, on how to use a library).

An SDK (Software Development Kit) is a set of tools and documentation, or kit, that work together to help you use a particular library or develop a specific kind of software.

A GUI (Graphical User Interface) is the part of a software that allows the user to interact with the program through visual representations and controls (buttons, edit boxes, etc.).

So, Windows Forms, MFC and Win32 are basically different GUI libraries, specified and used by their respective APIs. Furthermore, they each have a number of tools to help you develop software with those libraries. Some of these tools are bundled into (downloadable) SDKs, but others come as plugins to an IDE (Integrated Development Environment). So, the whole drag-and-drop style tools would be most accurately described as a GUI Design Tool (or Environment). That's what I usually refer to them as, GUI designers or just GUI tools, or GUI makers. Sometimes, you might also hear people use the term "RAD tool" to name such tools, here, RAD stands for Rapid Application Development. Although, to be rigorous, this term could be used for other tools too, often, programming-based tools for specific application domains (like database apps, automation, etc.).

By the way, as I understand that Windows Form Application that I'm talking about is …

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

Where "user-defined" gets attributes from "original", do you understand what is my spot of stumbling?

You must look at it as typedef <declaration>;. If you see that int var; is the declaration of a variable var, and that int func(int i); is the declaration of a function func. So, typedef int var_type; is a definition of a type equivalent to int, and similarly, typedef int func_type(int); is a definition of a type equivalent to a function taking an int as parameter and returning an int.

I agree that the syntax of function (-pointer or -reference) types is a bit counter intuitive or confusing. That's just the way it is, and read the relevant parts of the standard like I suggested, it will be much clearer then.

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

I'm sorry to hear that....

We're supposed to answer questions on this forum, and I didn't see any question in your post. But I can comment.

What baffles me is that you have such an interest for programming that you've persevered for over a year dabbling in it, but at the same time you express immense frustration at it.

First, I don't know what process you have followed to learn C++, but it sounds like you've been doing a lot of brute force and trial and error. This is really the hard way to go about it. You might need more structure. Get a good book on programming in C++ (like C++ Primer Plus or Accelerated C++), and follow it with patience and rigor, read it well, and make sure you understand every concept and test them out. If there is anything along the way that you don't understand, don't skip over it, get to the bottom of it either through googling, testing with some code, or coming back here with questions about it. Building an understanding and skill in programming is like building a house, you can't throw bricks together randomly, you have to build it from strong foundations and going up.

Second, you must be aware that C++ is far from being the only language out there. It certainly is a very important programming language (and dominates in many fields) that any professional programmer will / must eventually learn thoroughly. But C++ is certainly not the easiest language …

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

void h(void i() throw(int));

That is the declaration of a function called h which has no return value and takes one parameter, called i, which is a function with no return value and no parameters and that can only throw an int. When it comes to functions, you can have function types, function-pointer types, function-reference types, and all of those for member-functions as well. I know this can be confusing, even more so because these three types have implicit conversion rules between them (a function can implicitly convert to either a function-pointer or function-reference, and vice versa, and the same goes for member functions). There are few good explanations of this, and if you really want to understand it clearly, read the relevant sections of the C++ standard document, in particular (in draft n3337): 3.1, 3.9, 4.3, 8.3.5-6, 8.4, 13.4, and, of course, 15.4 (where the IBM page got its quote and examples from, and the C++ standard is much clearer than the IBM page on this). When you read the sections of the standard pertaining to function types and such, you eventually get an epiphany and realize how it all works.

Internally, it really doesn't matter much which type you have between a function type, a function-pointer type or function-reference type, they are probably all treated pretty much the same by the compiler.

Here are a few examples that might clear things up:

typedef int F(int);      // function type F.
typedef int (*pF)(int);  // function-pointer …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The best way to find out is to try them out. There are many non-trivial issues beyond what you can reasonably predict based on theories (time-complexity or whatever else). It also depends on the factors that rubberman mentioned. The fastest traversal is always going to be with compact and contiguous memory (i.e. array) but you'll pay the price at insertions / deletions. The fastest lookup is, of course, hash tables (constant-time lookups, like looking up by index), but you pay the price in design complexity (finding a suitable hash function). The main factor for performance is predictability, meaning that the architecture (cache pre-fetchers and branch predictors) has to be able to easily predict what you will do next, this often results in 10x to 200x faster code (this is why linked-list traversals are usually too slow to actually be useful).

Basically, the holy grail is constant-time lookups and linear-time traversal (with low constant factor). A finely tuned hash function will give you constant-time lookups on average. Compact arrays will give you linear-time traversal. Having both at the same time might be very hard. There are trade-offs every step of the way.

Given a set of elements, you could, in theory, use the data to infer the best possible hash function, and then store the elements in an array, so you'll get the fastest possible lookups and traversals, but you pay a very high price if the elements change in any way (you have to recompute the hash function, and reorder …

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

Like a goat on a redneck's farm. (just kidding!)

How can rotten fish (surströmming) constitute a gourmet meal?

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

You have an error with this line:

relativeX = (relativeX*cos(angInRad)) - (relativeY*sin(angInRad));
relativeY = (relativeX*sin(angInRad)) + (relativeY*cos(angInRad));

because you set the relativeX value and then use it again in the next line. You need to preserve the original value of relativeX until you have computed relativeY. This is probably what explains the weirdness happening when you do a lot of rotations. So, you should do:

double newRelativeX = (relativeX*cos(angInRad)) - (relativeY*sin(angInRad));
relativeY = (relativeX*sin(angInRad)) + (relativeY*cos(angInRad));
relativeX = newRelativeX;

As for your problem with +1 and -1 rotations, this is basically a problem with truncation vs rounding-off. Conversing a double to an integer will truncate the decimal part, not round it off. This means that, in the case of +1 rotation, you will get X: 335.35 -> X: 335, while in the case of -1 rotation, you will get X: 334.65 -> X: 334. If you care about this one pixel difference, then you should use a round-off of the values (the way to do rounding in C++ is to use std::floor(x + 0.5)):

p2[0] = std::floor(p1[0] + relativeX + 0.5);
p2[1] = std::floor(p1[1] + relativeY + 0.5);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I don't know what this means even after looking online, I'm going to guess the pointer isn't being deleted, so maybe somebody could help me.

If a pointer wasn't deleted, the program would not crash, only leak memory (which the OS will reclaim anyways). I'm pretty sure that this error is due to deleting a pointer twice, or attempting to delete a pointer that doesn't point to memory that was allocated on the heap (either an uninitialized pointer, or a pointer to a stack-based object or array). This is a classic heap-corruption error (asking the heap to do something that doesn't make sense like deleting memory that is already free or deleting memory that doesn't belong to the heap (or that heap)).

I'd like to be able to help you find the problem, but it's impossible with the code you posted. Clearly, the error is in your implementations of the constructors, copy-constructors, copy-assignment operators and destructors, but you didn't post that code, only the interfaces of your classes. Since all I can look at is the interface, I'll comment on that.

First of all, you are missing the assignment operator for your Matrix class. The standard form for the copy-assignment operator is one of the following:

Matrix& operator=(const Matrix&);
Matrix& operator=(Matrix);

What you have in your code is the following:

Matrix& operator=(Matrix*);

This is wrong, and it won't be recognized by the compiler as a viable alternative for the copy-assignment operator, and thus, the compiler will …

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

Because it can't fly under water.

Why does the Tower of Pisa look straight to me?

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

is there any problem with initializing those pointers with the initialization list of the constructor?

No. It's perfectly fine. But you need to know what to do with the pointers once your object contains them (is your object responsible for deleting it? (hint: it cannot).. can you guarantee that the objects pointed to will always exist during the life-time of your object? (hint: you can't).. etc.). So, there are problems associated with using raw-pointers, but nothing related to initializing them in an initialization list (in fact, that is recommended). For more info on the ownership of objects and the dangers of raw pointers, consider reading my tutorial on the subject.

is there any problem with initializing members of a class and passing parameters to the base class constructor in the same initialization list?

No. This is exactly what initialization lists are great for. In fact, you can't pass parameters to a base class constructor in any other way. And I don't understand what you mean by "in the same initialization list?". There is just one initialization list in a constructor, and it is called a "list" for a good reason, you can do many initializations of base-classes and data members (formally called "sub-objects"), as long as none appear twice in the list (of course!).

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

If you compile with a very strictly standard compiler, then that line will indeed produce a compilation error. For instance, you can try it with the online Comeau compiler (pretty much the most standard-compliant compiler that exists).

I'm not surprised that many compilers do not care about this exception-specification-related rule. Most compilers are not strictly compliant with the standard, they cut a few corners short (usually nothing major), especially with things that nobody cares about. Exception specification is one of those things. It's just a cost-benefit thing here. If you want to enforce this rule of the standard, you need to do static analysis of the code to cross-check exception specifications, and it can be quite hard (and wasteful). Then, most of the actual purpose of exception specification is for run-time halts when an unspecified exception tries to propagate out of a function, this feature has no purpose under static analysis (during compilation), it only serves a purpose after compilation. Then, considering that there are real problems with the actual usability of exception specifications in general (the intent is good, but the design is flawed in a way that makes them pretty much useless), this makes exception specification a very rarely used feature, whose use is generally discouraged (except for the "no-throw" specification), and the compilers support it mostly for legacy reasons (and with the introduction recently of the noexcept specification, I think the long-term aim is to get rid of exception specification altogether). Conclusion: nobody cares much …

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

Here is an example of a recursive function (the print_countdown function, ignore the rest), you can copy-paste it and try it out:

#include <iostream>
#include <iomanip>

#ifdef WIN32

#include <windows.h>

static std::size_t get_stack_size() {
  MEMORY_BASIC_INFORMATION mbi;
  VirtualQuery(&mbi, &mbi, sizeof(mbi));
  VirtualQuery(mbi.AllocationBase, &mbi, sizeof(mbi));
  VirtualQuery((char*)mbi.BaseAddress + mbi.RegionSize, &mbi, sizeof(mbi));
  VirtualQuery((char*)mbi.BaseAddress + mbi.RegionSize, &mbi, sizeof(mbi));
  return mbi.RegionSize;
}; 

#else

#include <pthread.h>

static std::size_t get_stack_size() {
  std::size_t stacksize;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_getstacksize (&attr, &stacksize);
  return stacksize;
};

#endif

void print_countdown(int i) {
  int new_i = i - 1;
  std::cout << "\rCountdown to stack-overflow: " << std::setw(7) << new_i; std::cout.flush();
#ifdef WIN32
  Sleep(0);
#else
  usleep(0);
#endif
  print_countdown(new_i);
};


int main() {

  print_countdown(get_stack_size() / (8 * sizeof(std::size_t)));

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

Glad you appreciate my help.

In the Delete function you just posted. you are missing a break; statement between lines 13 and 14. Once you find the matching name in the list, you need to break out of the for-loop.

And yes, the scoping within a switch-statement carries throughout the cases. Think of it this way, scopes equal opening and closing curly braces. And, for switch-statements, don't forget the break; statement after each case (otherwise, the subsequent case will be executed as well). Put simply, switch-statements are weird, I don't like them very much, I think the syntax is awkward, but that's just my opinion (thankfully, switch-statements are rarely needed, at least, not when you know better ways).

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

In the newest standard, this function should be found under the #include <numeric> header. Also, I'm pretty sure that GCC has had this function and header for a long time (they list it as part of their 1998/2003 standard library, although it shouldn't be, to be strict) so it should work, not so sure about MSVC though.

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

red -> dragon

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

If I put nothing in the "are you human" boxes, it tells me that the fields are required.

If I put the answers in the boxes, it tell me nothing, doesn't post anything, and the questions change to something else, after which I can repeat indefinitely.

At all times, it tells me that I should fill in the boxes in the "Join Daniweb" section, but that defeats the purpose of posting as a guest, doesn't it?

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

I tried to post while logged out, it didn't work (using Chrome if that matters). I never seem to pass the "are you human" questions, which I think is wrong, unless I'm actually a robot.

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

Codemirror suppresses the browser's spellchecker highlighting

Then, drop the codemirror, IMO.

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

Calm down. There is always a good explanation for everything.

Your problem is with the lines 41 and 42. You are returning a pointer to a local variable. That variable happens to be a pointer as well, but that doesn't change anything. Your function returns a pointer to a local pointer variable. That pointer variable quickly goes out-of-scope when the next iteration of the for-loop begins. I suggest you do this instead:

f(*currEntry == 0){
  // the head is the first node
  *currEntry = newEntry;
  return currEntry;
}else{
  // attach the node to end of the list
  (*currEntry)->SetNext(newEntry);
  return &((*currEntry)->Nextnode);
}

That should fix your problem.

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

The code you posted is illegal, should not compile (if it does, go complain to your compiler-vendor).

When you declare an array, with a line like this:

int a[5];

Then, the number between the brackets is the total number of elements in the array (in the above, it's 5).

When you address a specific element of the array, as so:

a[0] = 42;

Then, the number between the brackes is the index of the element that you are accessing. In C/C++, and in most other programming languages (except Matlab and Fortran, ASAIK), the first element of the array is the element 0, and the last element would be element n-1 (n being the total number of elements in the array). This is why you will normally see for-loops written like this:

for(i = 0; i < n; ++i)  //note that at the last iteration, we have 'i == n-1'
  a[i] = 42;

The reason why your code is invalid is simply because C does not allow a zero-size array to be declared (because that's impossible). In C++, zero-size arrays are fairly common as a way to trip the compiler into producing a compilation error if you try to do something that shouldn't be done, in C however, there isn't much use for that.

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

The -o is to specify the output of the compilation, so, when you right:

$ g++ -o test.cpp RefEnv.cpp

You are telling the compiler to compile RefEnv.cpp and produce an executable file called "test.cpp", and because RefEnv.cpp doesn't have the main function, you get the error that you get. So, you need to write this:

$ g++ -Wall test.cpp RefEnv.cpp -o test.exe

(I added -Wall which you should always use).

Or, if for a unix system:

$ g++ -Wall test.cpp RefEnv.cpp -o test
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

AD's right. The problem is probably with the return values of the set functions. I don't see anything else that could be wrong. Basically, if you don't return a value, then that creates an uninitialized value. This is simply because the memory for the return value is normally pre-allocated before entering the function, and then the function fills that memory with the return value (i.e. it is constructed in-place). If you have a function declared with a return type and then call it without assigning the return value to anything, it will just create a temporary variable for the return value, and that temporary will be immediately destroyed after coming back from the function call. If, on top of that, you don't have a return-statement in your function, then when you get back from the called function, the temporary variable is uninitialized and set for destruction, which is likely to crash (but often not, which explains the 4 successes and 1 failure).

So, do as AD suggests, make the return-type void for the set-functions. Also, you should always compile your code with the highest level of warnings (in GCC: -Wall, in MSVC: /W4), because an error like this would be caught, GCC would say "warning: control reaches end of non-void function." which is the kind of message that would have saved you a lot of time looking / asking around.

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

Imagine I'm the user of your class. I'm not interested in knowing about T0 or T1. I don't care about how the class keeps the time periods. All I want is a clear way to use the class, e.g., start, stop, and get elapsed time. Thus far, your implementation seem OK, but your class is confusing to use. Why do you need to bother the user with the T0 and T1 business. Consider simply renaming your functions: startSetT0 -> Start, stopSetT1 -> Stop, getT0 -> getStartTime, getT1 -> getStopTime, getT1 -> getElapsedTime, and printTimeConsumed -> printTimeInfo.

A lot of the art of OOP is to make classes with clear semantics (that are easy to use and understand) while hiding any implementation detail that the user doesn't have to know or care about (like t0 and t1 in this case). This can make all the difference in the world.

Also, your header starts with:

#pragma once
#include <iostream>
#include <cmath>
#include <ctime>
#ifndef CPUTimer_h
#define CPUTimer_h

the #pragma once is redundant with the #ifndef CPUTimer_h because both serve the same purpose, they are header-guards. And the includes should also be within the header-guard. Thus, you should just have:

#ifndef CPUTimer_h
#define CPUTimer_h
#include <iostream>
#include <cmath>
#include <ctime>
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If God really exist, then just imagine that the developer of this website(God) telling us how he created this website. How he programmed and how he designed this website.

Well, that makes God a "she", not a "he". We all have prior knowledge of the process of creating, hosting and maintaining a website, we know it's a man-made thing, and thus we know there must be one or more people behind the creation of such a website. We also have access to the world outside that website, can look at its source code, can talk to its author(s), can read about its history, etc... A lot of these things are critical in being able to figure out that someone created this website and to have means to determine who. Even without all the outside and prior knowledge (assume you were completely unaware of a world outside Daniweb), you can still PM or see posts from the creator "cscgal", and you could even test her divine powers (as admin), and that could be enough to convince you that she is a goddess on this website and that she probably created it. The analogy with the natural world is so far off. Everything you need to draw any of the conclusions (act of creation, existence and identity of God) is not available in the real world (no outside knowledge, no prior knowledge of any mechanism that would allow a God-like figure to create a universe, no definitive and reliable record …

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

This happened to me a couple of times before, usually after switching to an experimental version of GCC from the svn development branch. Switching to a stable release or a newer version should fix the problem. This is definitely a problem with the compiler (GCC is usually pretty bug-free, but once in a while, shit happens).

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

Every operating system I have ever come in contact with (except for DOS) has had enough memory protection to shut your program down if you try to write to memory that doesn't belong to your program, so it's not like you could end up writing a program that accidentally trashes your entire computer.

Managed-memory environments like JVM and .NET were never meant to protect the computer from being screwed up by careless programmers. Of course, do all the crazy stuff you like with pointers, and the worse that will happen is that your own program will crash. When you consider a virtual machine (and garbage collector) from a point of view of managing allocation / deallocation of memory and protecting against wrongful read / write operations (out-of-bounds, and such), the whole idea is to protect the programmers from themselves, nothing more, it has never been about protecting the OS or the user's computer, or the other programs. That would be like saying that the cushions on a wall are there to protect the walls from the mental patient, of course not, the cushions prevent the mental patient from cracking his own skull, the walls will survive. The JVM or .NET work in a similar fashion, they don't protect the OS or the computer, they form a cushion layer so that the programs running inside them can't hurt themselves too much. This is not a bad idea at all, but it can cost a lot in terms of performance, …

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

Nobody wants to pay someone to learn, unless it's for a permanent position (learn for a while and then be a productive employee for several years). Your level of experience, as you described it, is minimal, you still have a long way to go kid.

Your best bet is probably to get involved with some open-source project that you find interesting and / or do a Google Summer of Coding (GSoC) project, or something similar. That will get you on your way to building some credentials that might get you a foot in the door of a company. The credentials you described are basically negligible (they roughly correspond to the credentials I had when I was 14-15, and only several years later did it even cross my mind that I now had enough credentials to be paid for using my skills). Your question kind-of sounds like "hey, I know what a wrench is and I can screw / unscrew bolts, will you pay me to fix your car? I'm a quick learner, you know...". It just doesn't work that way. Even having done a complete course in car mechanics often wouldn't even be enough to convince someone to pay you to fix their car (due to risk, longer time spent, or increased cost due to lack of experience). Programming is very similar to that, it takes credentials for people to trust your skills and pay you for them (credentials may or may not include education (degree), but it certainly requires …

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

If you hold an array of Y objects, then you can only store Y objects in it, nothing else. When you do stuff[0] = Z();, what you are really doing this is: create a temporary Z object, and then assign a Y object (the first in the stuff array) to be equal to the Y part of the temporary Z object (which is itself destroyed shortly after). So, all that remains in that slot of the array is a Y object, it's as if the Z object never existed. A good compiler should warn you about this, I think.

If you want to store polymorphic objects (e.g. objects of any derived class) inside an array, you have to use pointers (or references, which is rather impractical in this case). That's just the way it is.

Is this the reason more modern languages like C# use interface type situations and Handle Classes under the hood as references/pointers?

Well, "modern" is subjective a bit, but I don't want to start another rant on that. Some languages use reference-semantics, while C++ uses value-semantics. In C++, everything is a variable (or "value") with a defined location in memory and a size which are fixed at compile-time, i.e., we call that a deterministic memory model (meaning that you can always predict exactly when a variable is created and destroyed, which is at declaration and at scope exit, respectively). Now, you can also use freestore (or "dynamic memory" or "the heap") to store objects …

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

Has anyone been able to see it with their own eyes?

Well, through telescopes, yes! The observations of red-shifts in the light coming from cosmic bodies all around our own is a direct observation of an expanding universe. In some sense, we are, right now, in the middle of this enormous and accelerating expansion, and that's the Big Bang, nothing more. So, if you are referring to if we have observed the very "start" of the Big Bang, then the answer is no. But we can observe the state of the universe at various points in time, long long ago, all the way to the last scattering surface (first time light could propagate) which is also called the microwave cosmic background radiation. Imagine this, we have a kilo of C4 that we film at high-speed while it is ignited, but then we realize that the first few frames are missing (camera malfunction or something), but you can still clearly see the initial shock-wave, the thermal expansion, the idiobatic expansion, and the subsequent subsonic flows of hot air (usually, carrying debris). Could you honestly say that the video footage doesn't "prove" that there was an explosion? Of course, nobody can tell from the video what the source of the explosion was (Was it C4 or TNT? Or magic fairies?), but an explosion occurred, no doubt, and you can even use the video to calculate the amount of energy released by the explosion. The Big Bang is very similar in …

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

I think you are a bit confused about how instructions are executed on a virtual machine.

The "stack" is not a stack of instructions, that's why you are confused on how to set it up. The instructions themselves are more appropriately stored in a queue or stored in a random-access array (e.g. vector or deque), i.e., a virtual equivalent of the magnetic tape of the original Turing machine. Instructions are not stacked up, they are queued for execution and occasionally jumps are made (for conditionals, loops, or function calls). If you don't allow those flow-control constructs, then you can stick to just a queue of instructions, in which case, all you do is pop the instructions off the queue and execute them until there's nothing left on the queue.

As for the representation of the instructions, I think you definitely need a base-class with a virtual function to execute the operation. This is because each operation will require different operands which have to be embedded in them, so you might as well bundle that in an object.

What is commonly referred to as just the "stack" is the memory stack used by the code to store the variables used during the execution. You're gonna need that. But, unless you want to make your virtual machine an emulator of a real instruction set, what you might not need are the general-purpose registers. In real CPUs, the registers are used because they are stored directly on the CPU such that they can …

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

Science can't prove or disprove the existence of (a) God. Why should it try?

It doesn't, never has, the starting point for scientific inquery is an observable phenomenon, if there is ever an observable phenomenon that would seriously indicate the presence of a God, scientists would investigate it, so far they never had to, for obvious reasons. Science has never said much about the existence of God except repeatingly telling those who claim his existence: "Sorry, I don't believe you, come back when you have evidence for your claims.". To me, science is a filtering method to get to the truth (in whatever realm, from physics to sociology) making sure that claims have reliable evidence to justify them before they are accepted. Organized religions have historically hated science because (1) religions know that their claims can't pass that filter and never will (because the nature of their claims prohibits or avoids falsifiability), and because (2) science keeps exposing them for the fraud that they are. But don't get me wrong, people are totally free to be part of or adopt whatever non-sense fraudulent organisation or belief system they want, that's none of my business, but I can surely try to convince them otherwise.

Unless certain movements wish to propagate bad science (e.g. Intelligent Design), or stifle the human rights of specific minorities in society (e.g. gay community) perhaps we should allow them their beliefs?

Right on. That's exactly what I meant by "As long as both …

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

"C# is like a newer version of C++" -- Microsoft's Ministry of Public Enlightenment and Propaganda

Here goes another rant:

C#, like most other programming language that came after C/C++, has a syntax that is largely based on or similar to C/C++. This is purely to ease the adoption of the language, in the same way as all cars have a steering wheel and pedals, but that doesn't mean that Toyotas are the newer versions of Fords. There is only one language that is truly the "newer version" of C++, and that is, the newer version of C++! I.e., the new language standard called C++11.

Personally, I don't even consider C++/CLI to be a newer version of C++.

Even Microsoft is beginning to realize that all the efforts that they have been deploying in the last several years to try to squash C++ (and other languages) in favor of their own proprietary languages that depend on their own proprietary platforms (.NET or Silverlight) which effectively depend on their own proprietary operating systems is just another painfully obvious attempt at "vendor lock-in" that programmers just aren't buying anymore (but sadly, some companies and academic institutions will chow down any pablum that Microsoft serve them, and they especially target the third world).

C# is as similar to C++ as Java is. In fact, most of the time, from a perspective of describing the design principles of programming languages, you almost always end up putting C# and Java in the same …

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

There have been some attempts at combining GIL and OpenCV, and two distinct projects on the GIL website are about the development of such an extension, see here. I wouldn't exactly qualify OpenCV as a well designed library (much less than GIL), but it certainly is very feature-rich. The OpenCV code itself is pretty messy, the docs are a sparse and unclear, and there are some weird decisions entrenched in the design, not to mention that there are multiple incarnation of OpenCV and they are all mixed together for backward compatibility (the latest incarnation tries to make more use of templates and generic programming techniques). So, it is somewhat of a tangled web, at least, that's the impression I got the last time that I looked through the OpenCV library and used it for some stuff, but the things that it can do and the algorithms available in it are pretty awesome. This is yet another installment of the everyday dilemma between a well-designed, generic but feature-deprived library, and a feature-rich but messy library. But if people could use GIL and still get access to the algorithms of OpenCV, it might be an incentive to turn their algorithm-development efforts to GIL, given its superior design.

Integration to Qt would mostly involve creating a new widget to display GIL images, and that's not very difficult. A while back I needed to display some images loaded with FreeImage (a basic image-loading library) on a Qt widget and it was a …

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

If you have some time on your hand, here is a great article on Linux vs. Windows from an IT professional's perspective (Spoiler: Linux crushes Windows!).

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

Use the code I posted:

glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, sprite.w * sprite.dx, sprite.h * sprite.dy, 0);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, sprite.w, sprite.h, (isBigEndian() ? GL_ARGB_EXT : GL_BGRA), GL_UNSIGNED_BYTE, sprite.data);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Is it no longer true that all textures must be of size 2^n x 2^n?

Since OpenGL 2.0 (2004), the hardware is required to support NPOT textures (and btw, the power-of-two rule is per-dimension, it doesn't mean that the texture has to be square!). This doesn't mean that all hardware will support it well or natively, it might lead to inefficiencies, but I would think that recent hardware (less than 5 years old) shouldn't have any problems with it. However, there are still reasons why power-of-two textures are preferable (mipmapping, filtering performance, etc.), so you should still prefer to make textures with power-of-two sizes. But if you absolutely need to use a NPOT texture, it will work, usually, in this day and age. But for maximum compatibility, you shouldn't rely on that and use the other method that I posted.

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

The Boost Graph libraries have an implementation of A* (and Dijkstra if you want) which both rely on a priority queue implementation that has more capabilities than the standard priority queue. Their priority queue implementation is also indirect which is also helpful. It supports functions like push_or_update, update, and contains which is really all you need for A*, which is lacking from the standard implementation. This queue is called d_ary_heap_indirect and here is a simple example by daviddoria on using it (among other nice examples of BGL). There is also a slightly more feature-rich and non-BGL priority-queue implementation available in the latest version of Boost called just d_ary_heap.

And btw, checking if a node is in the open list by checking if it is present in the priority queue is really inefficient. Most algorithms rely on a coloring scheme (or masking) meaning that you store, for each node, a status flag (or color) which tells you whether the node is open or closed (or un-discovered, or inconsistent, etc, depending on the variation of A* that you are implementing). It's very easy, as part of your algorithm, to make sure that the state of the flag is consistent with what set or priority-queue the node is in, because you control when nodes are moved in and out of the sets. I encourage you to either use the BGL implementation of A* or to at least check it out, see it here:

_Nemesis_ commented: Clear, concise response +0