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

The two functions that I posted (input and output) should be free functions (not members of the Rational class). You can simply insert them after the class declaration and before the main() function. Or, you can put them after the main function, but then, you have to insert the declarations between the Rational class declaration and the main function, as so:

class Rational {
  //.. 
};

ostream& operator << (ostream& out, const Rational& rat);  // declaration.
istream& operator >> (istream& in, Rational& rat);         // declaration.

int main() { 
   //... ...
};

// then, somewhere here, insert the code I gave, verbatim.

The error message you got is because those functions should not be member functions of the Rational class, they must be free functions (outside the class, so, no Rational:: should appear).

And, remember to make the two get-functions const as I said earlier. Otherwise, you'll get an error like this:

error: passing ‘const Rational’ as ‘this’ argument of ‘int Rational::getNumerator()’ discards qualifiers [-fpermissive]
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

What about a while loop? Something like this:

  boolean shouldContinue = true;
  while(shouldContinue) {
    shouldContinue = false;
    input = JOptionPane.showInputDialog("Enter a number between 1 and 10 " +
                   "and I will convert it to a Roman numeral: ");
    num = Integer.parseInt(input);
    if (num == 1)
       JOptionPane.showMessageDialog(null, "I");
    else if (num == 2)
       JOptionPane.showMessageDialog(null, "II");
    else if (num == 3)
       JOptionPane.showMessageDialog(null, "III");
    else if (num == 4)
       JOptionPane.showMessageDialog(null, "IV");
    else if (num == 5)
      JOptionPane.showMessageDialog(null, "V");
    else if (num == 6)
      JOptionPane.showMessageDialog(null, "VI");
    else if (num == 7)
      JOptionPane.showMessageDialog(null, "VII");
    else if (num == 8)
      JOptionPane.showMessageDialog(null, "VIII");
    else if (num == 9)
      JOptionPane.showMessageDialog(null, "IX");
    else if (num == 10)
      JOptionPane.showMessageDialog(null, "X");
    else {          //error message   
      JOptionPane.showMessageDialog(null, "Not good at following instructions?" +
                                            "\nI said enter a number between 1 and 10!");
      if( JOptionPane.showConfirmDialog(null,
                 "Do you want to try again?",
                 "Try again?", JOptionPane.YES_NO_OPTION) 
                  == JOptionPane.YES_OPTION )
        shouldContinue = true;
    };
  };
  System.exit(0);

Or, you can do it slightly differently if you want to allow retries even if the person entered a good number. You get the basic idea here: use a while-loop and set the flag depending on what happened in the loop, to trigger a repeat or not.

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

Did it occur to you that you can test this out very easily? When it comes to performance, the only thing that can settle the argument is test results, the rest is just speculative non-sense. Try this:

#include <iostream>
#include <ctime>
#include <algorithm>
#include <cstring>
#include <iomanip>

union Record {
  struct {
    double x,y,z;
  };
  struct {
    double Magnitude, Direction, Angle;
  };
};

using namespace std;

int main() {

  const int X = 10000;
  const int Y = 10000;

  Record* p_records = new Record[X * Y];

  int k = 0;
  clock_t t_start = clock();
  for(int i = 0; i < X; ++i) {
    for(int j = 0; j < Y; ++j) {
      p_records[k].x = 0;
      p_records[k].y = 0;
      p_records[k].z = 0;
      ++k;
    };
  };
  clock_t t_end = clock();
  cout << "First method took: \t" << setw(10) << (t_end - t_start) << " clocks." << endl;

  t_start = clock();
  for(int i = 0; i < X * Y; ++i) {
    p_records[i].x = 0;
    p_records[i].y = 0;
    p_records[i].z = 0;
  };
  t_end = clock();
  cout << "Second method took: \t" << setw(10) << (t_end - t_start) << " clocks." << endl;

  t_start = clock();
  Record* end_records = p_records + X * Y;
  for(Record* p = p_records; p != end_records; ++p) {
    p->x = 0;
    p->y = 0;
    p->z = 0;
  };
  t_end = clock();
  cout << "Third method took: \t" << setw(10) << (t_end - t_start) << " clocks." << endl;

  t_start = clock();
  Record zero_rec;
  zero_rec.x = 0;
  zero_rec.y = …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is a great start! You have clearly put some effort into it.

The easiest way to solve this problem with the inputs of the rational numbers is to create a separate function for inputting and outputting a rational number. And the best way to do this is to overload the << and >> operators for the iostreams. By simply taking your code and putting it into the following functions:

//output operator, to print a Rational number:
ostream& operator << (ostream& out, const Rational& rat) {
  out << r.getNumerator();
  if(r.getDenominator() != 1)  // print denominator only if it is not 1.
    out << "/" << r.getDenominator();
  return out; // don't forget to return the ostream object.
};

//input operator, to input a Rational number from a stream:
istream& operator >> (istream& in, Rational& rat) {   // notice the & here.
  int num = 0, den = 1;
  in >> num;
  if(in.peek() == '/') {  //check if there is a denominator.
    char temp;
    in >> temp >> den; // read the denominator.
  };
  r.setNumerator(num);
  r.setDenominator(den);
  return in; // don't forget to return the istream object.
};

Notice that I used pass-by-reference in the above. In the first case, I pass a const-reference, which means that the variable (within the function) refers directly to the variable on which it was called, but without permission to change it. In the second case (input), I pass by reference (non-const), which means that there is permission to change the variable, and because it …

alsz commented: @Mike O_o I am so sorry , but how do you exactly implement the first part of your solution into my code or my code into your solution. I have never seen the istream and ostream. Do I have to declare them in the class ? +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The general rule is this:

  1. Prefer declaring / defining your operator overloads as non-member functions;
  2. If you need access to private members, make them non-member friend functions;
  3. If that particular type of operator must be a member function (like the assignment operator, or conversion operators), then make it a member function.

As for the difference between parameters as (Box B1) and (const Box& B1), well, that is just the difference between pass-by-value and pass-by-reference. Generally, for any non-primitive type (like a class), use the pass-by-reference, e.g., (const Box& B1).

As for your actual error (undefined reference), this is because you declared the operators are inline. When you declare a function as inline, its definition (implementation) must appear in the header file. So, to fix the problem, either you remove the inline keywords from the declarations, or you move the definitions to the header file (e.g., after the class declaration). Either way is fine. If the function is a simple one-liner function, then it might as well be inline and put in the header file, but for longer functions, there is no point in making them inline.

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

The number of pixels to allocate is width * height. You shouldn't have the BytesPerPixel in there. It should be:

Pixels = new RGB[width * height];

As for the crash, it might have something to do with the fact that your array, that TEMP points to, is too small for the image size in bytes. Because of the padding at the end of the rows, the total size in bytes of the image is not equal to width * height * BytesPerPixel, it is slightly bigger than that. You should use the value stored in Info.bmiHeader.biSizeImage as the number of unsigned char to allocate. As in:

unsigned char* TEMP = new unsigned char[Info.bmiHeader.biSizeImage];

And use the same size value in the memset().

Finally, don't forget to close the file handle at the end of the function (you do it in all the if-statements, but you forgot to do it at the "normal" end).

Other than that, I'm not sure what could be causing the crash.

triumphost commented: Solved all my problems :) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You've been busy! Pretty nice code you have there.

There is one important mistake for sure, you allocate your pixel array as Pixels = new RGB[size]; where size is the size in bytes of the image. So, you need to allocate the pixels as Pixels = new RGB[width * height];.

The second error is to make the assumption that (sizeof(unsigned) == 4) that may not be the case on some computers. If you want a fixed and known size, you need to use the header <stdint.h> (or <cstdint> if you have a recent-enough compiler), and use the type uint32_t in your union:

typedef union RGB
{
    uint32_t Color;
    struct
    {
        unsigned char B, G, R, A;
    };
} *PRGB;

Another bone I have to pick is with the throwing of a string literal. You shouldn't do that. Prefer to throw an exception object. The standard provides a few useful ones, or you can make your own classes derived from the std::exception class.

Now, to the point of your questions.

The bitmap format (uncompressed, at 24 or 32 bpp) stores the colors as Blue-Green-Red(-Alpha) in little-endian byte-order (i.e. the Blue byte is the least-significant and stored first). So, that is exactly how you should read the pixels from the file. And that is not what you are doing at all. And, you do have to consider the padding at the end of the rows (to make it an even multiple of 4 bytes). You cannot read the …

triumphost commented: Best reply and most helpful person. +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I know .NET is a Microsoft framework.

Yes.

I currently use Visual Studio 2008 for C++ programming in school. Am I using .NET?

Maybe. C++ is a programming language that is fundamentally incompatible with .NET. However, Microsoft has a frankenstein language called C++/CLI which mixes C++ with .NET code (and from my impression of it, it seems mostly intended (and used) as glue between real C++ code and real .NET code (e.g., C#), not as a standalone language). It might not be obvious to you which one you are using. But, technically-speaking, if you do C++ programming, then you are not using .NET, and if you do C++/CLI programming, then you are most-likely using .NET.

Here are some obvious signs that a given piece of code is in C++/CLI and not in C++.

  1. If standard library components use CamelCase convention, like String instead of std::string. All standard library components in C++ use all lower-case letters, usually underscore-separated.
  2. If you see things like System::Console::WriteLine( something ) as opposed to std::cout << something << std::endl;.
  3. If you see the character ^ anywhere. In C++, that character is not used for anything, and cannot appear in variable names either. In C++/CLI, it denotes a pointer.
  4. If you see things like ref class Something { to declare a class.
  5. If you see gcnew instead of new (gcnew means "garbage collected new"). In C++, there is no such thing as garbage to collect, so that doesn't exist.

and so on...

darkagn commented: An informative, concise and polite post +10
Perry31 commented: Thans Mike for your elaborate information and so patience +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, DeanMSands3 was right about one thing: the original loop was erroneous. The correct solution is this:

indices = malloc (sizeof(short) * data.face_count * 3);
for (i = 0; i < data.face_count; i++);  // notice i++ and not i += 3
{
    indices[3 * i]     = data.face_list[i]->vertex_index[0];
    indices[3 * i + 1] = data.face_list[i]->vertex_index[1];
    indices[3 * i + 2] = data.face_list[i]->vertex_index[2];
}

As for the weird behavior, it looks like a memory corruption to me. I would start by making sure the code is correct (like the above), and then start talking about "weird" behavior. In my experience, compilers (almost) never act in a weird way, but programmers do all the time!

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

The guidelines for the two algorithms are basically the same as for their respective mother-algorithms, i.e., the sorting algorithms.

The counting-selection algorithm is only applicable to a very tightly packed integer-valued array. What I mean by that is that the bound (cap in your function) has to be very small, underwise the memory consumption of the algorithm is really unacceptable. You see, the theoretical best algorithm for such a selection problem requires O(n) time and O(1) memory. The counting selection requires O(n + m) time and O(m) memory, where m is the maximum possible value in the array, this is significantly worse than the theoretically achievable performance. So, unless m is really small compared to n, it makes no sense to use this algorithm. And because you should be able to get O(n) time and O(1) memory for this problem, there is no reason to use this algorithm in any case, at least, from a theoretical point-of-view. If you do some comparative performance tests to show that for certain small array sizes and small bound on the values, that the counting-selection algorithm has sufficiently small constant-factor to make it faster than others in that regime, than that is your guideline.

As for the quick-selection algorithm, it is quite a bit better, with O(n) best-case time and O(1) memory, but it does have O(n^2) worse-case time. This algorithm applies in the general case (values don't have to be integers either) but it is not guaranteed to be fast in all cases, …

Sasstraliss commented: Very good explanation +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here are some initial comments:

Style
Overall the coding style is OK, but a bit unusual. Naming functions like Pull_randWord is a bit unusual, but more importantly, it is not consistent with the rest of the code, you should pick one style and make it consistent. Then, using all upper-case letters for class names is a big no no. If there is one convention that you should obey to is that of reserving upper-case names for MACROs and #defines, every programmer will expect all upper-case names to mean that (like HANDLE, which is a #define).

Practical coding issues
The header-guard on a single line is weird, better make it like this:

#ifndef HANGMAN_H
#define HANGMAN_H

You use some non-standard headers, like <conio.h> and <time.h>, you should avoid conio completely and replace <time.h> with the standard header <ctime>

#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>
#include <ctime>

Also, in your header file, you should avoid including headers that you don't need in order to complete the class declaration. The headers that you only need to implement the class functions should be included in the cpp file. As I see it now, the only headers that you need to complete the class declaration are <string> and <windows.h>. All the other headers, you should include them in the cpp file only, after the inclusion of your header file. This is a practical thing, it helps to avoid dependencies between header files and reduces compilation times, it's …

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

If the program finishes and there is still memory that wasn't deleted, it won't matter. The memory gets allocated by a thing called the "heap", which is a part of the program (something the compiler generates for you). This heap is like a manager of memory, it allows you to allocate and deallocate memory (via new and delete). This heap gets its memory by asking the OS for it. When your program ends, the heap is destroyed along with all the memory that it is managing, so it doesn't matter if there is still some memory that wasn't deallocated (by deleting it in your program). As a double safety, if the heap is also corrupted (which can happen, depending on the system, if you ask it to delete memory twice or if you ask it to delete memory that it doesn't own or that wasn't allocated before), then destroying the heap at the end of the program might not be able to release all the memory that it requested from the OS, if that is the case, it won't matter either because the OS also keeps track of what memory was given to which program, and if your program ends (end of the process), the OS will reclaim all the memory that was allocated to it.

What you do have to worry about, however, is having memory leaks (memory that you forgot to delete) within a running loop. The effect of this is that the memory consumption will grow incrementally …

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

Analogy: You are a thread. You're looking for a room in a hotel, which is the resource. Because you are not alone, there can be several people coming in and out of the hotel at unpredictable times. So, the question is, how do you make sure not to over-book the hotel? The answer is, you need a guy at the front desk keeping count of the number of people who checked in (and didn't check out yet), that's a semaphore. Of course, this requires that everyone is diligent enough not to go into a room without having checked in, and that no one forgets to check out, that's also true of threads when using semaphores.

A binary semaphore just means that the hotel has a total of 1 room. While a counting semaphore means the hotel has N rooms.

The problem is, if you only keep count of the number of people currently checked in, but you don't keep a record of who is assigned to which room, you get the problem that everytime someone checks in, you can't direct them to any particular room that is available. This is why the counting semaphore is not as useful, at least, by itself. There are some cases where it can be sufficient to just keep count (for example, when limiting the load on a system), but in many cases you need more than that (e.g., managing a resource pool), in which case you might use a counting semaphore as part of …

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

That program is equivalent to this:

if(A + B < 20)
  A = A + 5;
else
  A = A - 1;

Line-by-line, you have:

LOAD  A
ADD   B

Puts the variable A on the register, and then adds the value of B to that. So, it computes A + B.

CMP   20
JB    etq1

Compares the result of the previous lines (i.e., A + B) to the value 20, and jumps if the comparison results in a less-than case, that is, if A + B < 20. If not (e.g. "else") it computes this:

LOAD  A
SUB   1
JMP   etq2.

Which puts A on the register and subtracts one to that. Then, it jumps to label 2 (I assume that etq2 is an abbreviation for "étiquette 2").

If the comparison did yield a less-than case, then it executes this (at label 1) instead:

LOAD A
ADD  5

Which is obviously A + 5. And finally, in any case, at label 2, it executes this:

STORE A

which means that the current value of the register (either A + 5 or A - 1) is saved into the variable A.

En passant, deceptikon a raison, il vaut utiliser l'anglais, pour le bénéfice de tous.

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

There are a few issues with your code.

First, your ImplementCalculations function doesn't need to take those three parameters because they are already part of the class (and object). Also, you should probably name the function a bit better, like "ComputeOvertime" or something like that.

Second, you probably shouldn't call the display function from within the ImplementCalculations function. Keep things simple and separate. Call the ImplementCalculations function from the main function to compute those overtime hours and pay, and then, call the display function from the main function to list the employee information.

Third, to the main problem that you have. Summary information like Total_salaries, Total_hours, and Total_OvertimeHours should not be part of your EmployeeClass because they don't pertain to one individual employee. My recommendation is that you create a second class to store that information and implement the computation of those summaries in that class and also a display function for it. In other words, remove the three aforementioned data members from your EmployeeClass class and also, remove the Addsomethingup function. Then, create a class like this:

class WorkForceSummary {
  public:
    WorkForceSummary(EmployeeClass* employees, int employee_count);

    void Display();

    double total_salaries;
    int total_hours;
    int total_overtime_hours;
};

// ...

WorkForceSummary::WorkForceSummary(EmployeeClass* employees, int employee_count) {

  total_salaries = 0;
  total_hours = 0;
  total_overtime_hours = 0;

  for(int i = 0; i < employee_count; ++i) {
    // insert code here to sum up to employees[i].something
    //  and store those sums in total_salaries, total_hours and total_overtime_hours
  };

};

void WorkForceSummary::Display() {

  cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << endl; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you look at these two lines:

for (int j = 1; j <= i * i; j++) 
  if (j % i == 0)
    //..

The if-statement means that the iteration will only execute if j is a multiple of i. So, in combination with the for-statement before it, how many multiples of i do you have between 1 and i * i? Obviously, there are only i multiples of i between 1 and i * i. So, the two lines are actually equivalent to this:

for (int j = i;   // the first multiple of i is i. 
     j <= i * i;  // the last multiple of i is i * i.
     j += i)      // the next multiple of i is j + i.
  //..

Or, you could also write it as:

for (int l = 1; l <= i; l++) {
  int j = l * i;
  //..
};

which actually executes on i times, obviously. And because i is bounded by n, the complexity of that loop (merging the original for-loop and if-statement) is O(n).

So, using the above, we can reduce the for-loops to this:

for (int i = 1; i <= n; i *= 2)           // O( log2(n) )
  for (int j = 1; j <= i; j++)            // less-than O(n)
    for (int k = 1; k <= j * i * i; k++)  // less-than O(n^3)
      f=x*f;

From this, it is pretty trivial to …

thedarklord commented: Thank you very much, you helped me a lot +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yes. But there's a trap in the question. Pay attention to the if-statement:

if (j % i == 0)
thedarklord commented: I figured out that i is of base 2 like 2^l for example and th if statment is true when j is also of base 2 but in the inner is j*i so i don't know how to continue please help me +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Calculating the complexity of an algorithm is really just a matter of figuring out how many times an operation will be done.

If you take the outer loop, for(int i = 1; i <= n; i *= 2), you can ask yourself how many iterations will be executed. If n = 8, then you'll iterations i = (1,2,4,8). If n = 5, then i = (1,2,4). If n = 13, then i = (1,2,4,8). You get the idea? The number of iterations will be the log in base 2 of n, or just log(n).

You can proceed like this for the inner loops, each time you must multiply the results.

For loops that have inter-dependent bounds, like for(int j = 1; j <= i * i; j++), where the bound of the inner-loop is dependent on the value of the outer-loop, you can simply take the upper bound of the outer loop and assume some constant factor. That is, in that loop, the upper-bound is i * i where i is at most n, so you can consider the upper-bound of that inner-loop to be a constant factor times n squared, as in C * n * n, and since we don't care about the constant factor, you can just say that it is O(n^2).

I'll let you figure out the rest, since I get the feeling this might be a homework question.

thedarklord commented: Ok thanks for you help +0
Sky Diploma commented: :) +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

please note that i am reading a file that consits of all characters (ascii 0-255) therefore i must use wstring instead of string..

I doubt that this is true. A normal character (char) is one byte in size, and it can represent 256 characters (many of which don't actually result in any printed character). To read the bytes correctly (and in order) from the file, you should not use the wide-char versions of fstream, stringstream and string.

the file reading is stopped upon the occurence of first null character. how can i stop this from happening?

You read the values using the rdbuf which is a raw reading method. So, I doubt that the actual reading of the file stops at the first null-character (or zero byte). My best guess is that the content of the stringstream get cut-off either during the conversion to a string or during the printing of the string to cout. In any case, you shouldn't use a string to store and manipulate an array of binary data (non-characters). Try to use a vector of chars instead:

#include <sstream>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<char> readfile(const char* filename)
{
    ifstream infile(filename,ios::binary);
    vector<char> result;
    copy(istream_iterator<char>(infile), 
         istream_iterator<char>(), 
         back_inserter(result));
    return result;
}

int main()
{
    vector<char> data = readfile("hello.exe");
    cout << data.size() << endl;
    return 0;
}

BTW, the main function must return an integer (zero if all went well), this is required by the standard.

Humayoon Khan commented: very well explained =) thanks +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have a massive memory-leaking loop. No surprise that it crashes your system. In the loop inside main, you allocate B objects and never delete them. This is a more correct loop:

for(int i = 0; i < 1000000; i++)
{
    A* obj = new B();
    obj->foo();
    delete obj;  // this line is very important!
}

Also, when you need a temporary object only for the span of an iteration, you should just use a local variable, that is the favored mechanism in C++:

for(int i = 0; i < 1000000; i++)
{
    B obj;
    obj.foo();
}

Finally, DO NOT forget to make your base-class destructor virtual!!! This is very important to make sure that the most derived class destructor is called when you delete the object via a base-class pointer.

virtual ~A()
{
    cout << "ADest\n";
    delete b;
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

A) Does it already exists?

No. Unless you are working on a very unusual platform that has a native word size of 3 bytes (most systems have a native word size of 4 or 8 bytes, and some really small embedded systems might use 2 bytes natively).

B) If not, am I kinda on the right track for writing a class to fill the sweet spot between short int and int?

No. The processor will not be able to deal with a 3 byte integer value, you will have to put it into a 4 byte integer variable if you want to do anything with it. Also, even if you make a class that stores the 3 bytes individually, there is little chance that size of the object will actually be 3 bytes, because most compilers will add padding in order to align the size of the object to the native word size of the system (this is a fundamental optimization that all compilers will do).

but for a large data set this wastes a lot of space

Sure. If you store many numbers using 4 bytes when 3 bytes would do just fine, then you get a 33% increase in the memory used. But, if you try to pack all the numbers such that they each use only 3 bytes, I can't even imagine how horribly slow your program will become. The additional memory expense is worth the performance gain from using native …

Jsplinter commented: Solid explanations! +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

But does the compiler-generated move-constructor nulls out the source object?

No. Because what does it mean to "null out" the source object? There is no clear and general answer to this, it is a matter of context. For some objects, it is useless to "nullify" it (as in, set it to zero). For some objects, it would be erroneous to do so. And for other objects, it would correct.

For the compiler-generated move-constructor, the rule is pretty simple. If you have a class like this:

class Foo {
  public:
    Bar1 a;
    Bar2 b;
    //.. some member functions and stuff..
};

Then, the compiler-generated move-constructor will be exactly equivalent to this:

  Foo(Foo&& rhs) : a(std::move(rhs.a)), b(std::move(rhs.b)) { };

It's that simple. It will just use the move-constructors of all the data members of the class. This solves the problem of having to know how to move an object (nullify the source or not). The assumption here is that if you don't provide a move-constructor (or explicitely delete it), then the compiler can assume that it is correct to simply move all the individual data members (with their appropriate move-constructors). This is exactly the same assumption as for the compiler-generated copy-constructor, if you don't provide one, the compiler assumes that it is OK to simply copy the data members individually. In the case of a resource-holding class, like the int_vector in my tutorial, this assumption does not work, i.e., it is not safe to simply …

abdelhakeem commented: Very helpful explanation! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you allocated the arrays dynamically, then you don't have an array object to pass to the function, you only have a pointer to the first element of an array. In other words, the only option you have is to pass by pointer. If you store your 2x2 or 3x3 arrays as arrays of arrays, then you must have a pointer to a pointer. In other words, you'll have code that looks like this:

void printArray(float** p, int N, int M) {
  for(int i = 0; i < N; ++i) {
    for(int j = 0; j < M; ++j)
      std::cout << " " << p[i][j];
    std::cout << std::endl;
  };
};

int main() {
  float** p = new float*[3];
  for(int i = 0; i < 3; ++i)
    p[i] = new float[3];

  for(int i = 0; i < 3; ++i)
    for(int j = 0; j < 3; ++j)
      p[i][j] = i * 3 + j;

  printArray(p,3,3);

  for(int i = 0; i < 3; ++i)
    delete[] p[i];
  delete[] p;

  return 0;
};

That's about all there is to it. If you have any questions, please ask.

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

The correct ending for your main function is this:

  delete iVector1[0];
  iVector1.at(0) = new Test(21);
  delete pVec1->at(1);
  pVec1->at(1) = new Test(22);

  for(int i = 0; i < iVector1.size(); ++i)
    delete iVector1[i];
  for(int i = 0; i < iVector2.size(); ++i)
    delete iVector2[i];
};

As for the linking error, this is not an error in the code, but an error in the linking. Did you define the destructor of your Test class in a cpp file? If you did, you must compile both cpp files together (the cpp file with the main function and the one with the implementations of the functions of the Test class). The linking error simply means that the compiler cannot find the definition (implementation) of the destructor of the Test class.

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

As an online resource, this site is pretty much unbeatable.

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

Here is the thing with the "drawing a line". Draw a simple cartesian plot. Consider that 1 = true and -1 = false. Put a dot in the graph for each possibility (1,1), (1,-1), (-1,-1), (-1,1). According to XOR logic, only the points (-1,1) and (1,-1) yield "true" after a XOR. Can you draw a single line on that graph such that the two "true" points are on one side of it and the two "false" points are on the other?

The point with perceptrons is that all they can do is compute a linear combination of the inputs and use that to fire a 0 or 1 output (or through some other basis function). A "linear combination" is another word for a line, in fact, a line is defined by a linear combination of the coordinate variables (in this case, the coordinate variables are the inputs). So, literally, the only thing that a perceptron can do is draw a line and tell you on which side the input lies (0 or 1). So, this is why we say that a perceptron can only deal with a linearly separable problem, because that's all a perceptron does.

If you have a second layer in your ANN, you can get it to do two linear separations (e.g., two lines) and then combine those two outputs to figure out if the XOR output should 1 or 0. So, with one hidden layer, you can solve the XOR problem. It's that simple.

You must …

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

I hope you liked my tutorial, except for that one confusing part!

Isn't the compiler-generated copy constructor called if I used an rvalue like int_vector(int_vector(5))

No. The compiler-generate move constructor will be called if you used an rvalue like int_vector(int_vector(5)). In C++03, it would be the copy-constructor (and that explains the output from codepad) that is called, but not in C++11.

and it gets a shallow copy of the temporary object just like the move constructor?

Move-semantics is not the same as a shallow copy. A move-constructor will move the resource ownership from the source to the destination (constructed object). A shallow-copy doesn't move the resource ownership, it duplicates it, which is wrong. So, the shallow copy is only the first step in a move-constructor, the second, and crucial, step is to nullify the state of the source object. You need both steps. The default move-constructor will do the following:

MyClass(MyClass&& rhs) : member1(std::move(rhs.member1)), member2(std::move(rhs.member2), ... { };

In other words, it moves all the data members from the source object to the destination, and, of course, if a data member is of a primitive type (like int, float, or any raw pointer type), it will simply be copied. That is why you need to define your own move-constructor if you hold a resource like dynamically allocated memory, which is the point of my tutorial and the "Big Five".

I also thought that initializing the object with

int_vector(<temporary object>)

would call

int_vector::int_vector(const int_vector& …

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

there is also something called task manager, (which i doubt linux has) and a key combination known as Ctrl+C

Linux does have a task manager. Many different GUI-based task managers exist, depending on the distro. And, a series of command-line tools exist to do task management work, like ps (list processes), kill (kill a process), and top (monitor processes), and because you can do this from the command-line you can still do it even if the desktop environment has crashed (which is really rare), something windows cannot do.

And the CTRL-C or CTRL-Z to kill a command-line application (or console app) is actually part of a larger set of key-combinations that date back to Unix. In windows command prompt, it only provides a few of them, like CTRL-C. Under Linux, you have access to many more (more than I know), like CTRL-C (send kill signal to the process), CTRL-Z (halt the process right away), CTRL-D (detach the output of the program from the current terminal / console, i.e., run the app in the background), etc. etc.

Linux has nothing to envy windows on this front. In fact, for all sys-admin and all "having control on your computer" tasks, Linux leaves Windows in the dust, mostly thanks to the robust GNU tools with their long-standing and stable Unix background.

There is a reason for Linux being free, don't you understand?

Free and open-source software has a big advantage over commercial one, it is the only scalable model …

broj1 commented: Agree with every statement here +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

AD-star is not the most well-known algorithm amongst lay-people, but Likhachev's papers on the subject are quite easy to follow. I do recommend that you understand / use / implement A-star first, which enjoys a very wide amount of material out there to explain it in details. The wiki is a pretty good starting point. There are also many implementations of A-star available. If you dig good implementations at a high standard of programming, you can check out the A-star implementation in the Boost Graph Library. Similarly, if you want an AD-star implementation (exactly as described in Likhachev's work) in the same style and standard as the BGL A-star, you can check out my implementation of that here.

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

I think that your design is somewhat flawed. First of all, you require the catcher to know and require that the exception is one that is being logged, which you may not always want to do and may not be able to do in certain cases, leaving your catch-clauses very heterogeneous. Second, exceptions are common-place during the execution of a program, they aren't used only for completely erroneous occurrences, they are a mechanism to report out-of-the-ordinary conditions (and roll-back changes), which are sometimes quite common. Third, in your current implementation the thrower of the exception just throws a normal exception, and the catcher decides if the exception will be logged. I'm not sure that this is the best thing, but you can argue either way (that the thrower or the catcher should make that decision). Finally, as a general rule, you should keep the operations that occur during the propagation of an exception as simple as possible, to reduce the risk of a second exception being thrown, which would lead to an abort of the program (immediate termination). Also, opening and closing a file each time you want to log a message is too much stuff to do.

In light of these things, here is a somewhat more "professional" implementation of an exception-logger (while keeping it simple):

#ifndef EXCEPT_LOGGER_HPP
#define EXCEPT_LOGGER_HPP

#include <iostream>
#include <type_traits>

// Create a singleton class to access the logger's ostream.
class except_logger {
  private:
    std::ostream* destination;
    static except_logger& get_instance();
    except_logger(std::ostream& dest = std::cerr);
  public: …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

QWERTY here too.

I'm afraid your friends might be right, you are abnormal.

Personally, and especially for programming, I find that the placement of the non-letters in a QWERTY layout has more of an impact (and that is not significantly different in dvorak). With code-completion, you don't end up writing that many complete words, even if you choose good long and meaningful variable names. What you do type often is []{};:.<>!&% which are often different on different layouts, and that's really annoying when you use different computers, possibly in strange countries. And also, language plays its part, I can't use a layout that doesn't support french letters (accents and cdilles).

Is there a special keyboard layout that is really tailored for programming with easier-to-reach symbols that are common to most programming languages? I don't think dvorak qualifies.

|-|x commented: this.very(true); +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

For templates, the definitions of the functions must appear in the header file, if they are too long you can simple put them outside the class declaration, but still in the header file (i.e., after the class declaration). This is one of the few major drawbacks of templates.

Read this FAQ.

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

You don't need to use variadic templates for this. And you certainly don't want to go with the var-args solution that was suggested.

There is something called std::bind and std::function. The first allows you to bind any number of arguments to a function pointer and basically transform that function pointer into a different signature (and supply additional arguments). The second is a more general wrapper for all types of callable objects (function pointers / references, member-function pointers, functors, etc.), and that is the output of the bind function. In other words, you can do something like this:

double PNorm(double d1, double d2, int p) {
  return std::pow( std::pow(d1,p) + std::pow(d2,p), 1 / double(p) );
};

double Norm2(double d1, double d2) {
  return std::sqrt( d1 * d1 + d2 * d2 );
};

std::vector<double> GetNorms(const std::vector<double>& v1, const std::vector<double>& v2, std::function< double(double,double) > norm_function) {
  std::vector<double> result(v1.size());
  for(int i = 0; i < v1.size(); ++i)
    result[i] = norm_function(v1[i],v2[i]);
  return result;
};

int main() {
  std::vector<double> v1, v2);
  v1.push_back(0.5); v2.push_back(0.8);
  v1.push_back(2.0); v2.push_back(4.0);

  v_n2 = GetNorms(v1, v2, Norm2);
  std::cout << "Norm-2 are: " << v1[0] << " " << v2[1] << std::endl;

  v_n5 = GetNorms(v1, v2, std::bind(PNorm, _1, _2, 5)); // the _1 and _2 stand for argument one and two from the destination function signature.
  std::cout << "Norm-5 are: " << v_n5[0] << " " << v_n5[1] << std::endl;

  return 0;
};

I hope you get the idea. Read the cppreference pages on the subject, these things are also available …

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

Not only that but I'd have to constantly switch back and forth between headers and sources to see whats declared where or what contains what.

If it annoys you to switch back and forth between the header and source when you are implementing the functions, then here's a trick for you. Simply write the code in the header file (within class declaration), so you won't have to switch all the time, and then, once you have finished implementing and testing them, copy all the longer functions (longer than a few lines) into the source file, clearing them from the header file.

But now I'm looking up all my habbits to see if they cause performance degradation and I've read the first one does whereas the second doesn't :S

That depends on your definition of performance. The first one (definitions inside the class declaration) will lead to faster code at run-time, but possibly a larger executable at the end too. The second one will lead to faster compilations and fewer compilation dependencies (fewer needs for complete recompilations).

I'm also reading that if i put my definitions inside the class, it's automatically inlined

Putting the definitions inside the class will make the compiler attempt to inline the function by default. Inlining is never guaranteed, it is always up to the compiler to make that decision, whether it is worth inlining or not. And btw, inlining is a good thing, it is one of the most important …

triumphost commented: Very Very Amazing Post. I'll Change all My Files Now. +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Does ^ Replace the & operator?

No. The ^ is equivalent to *, while the % is equivalent to the &. Except that the ^ and % are for garbage-collected (or .NET) objects only. In other words, you allocate a GCed object with MyClass ^ obj = gcnew MyClass();. If you're going to do any C++/CLI, you should at least read up on the basics, the wiki page answers all the questions you asked so far.

triumphost commented: Very Very helpful. Solved it +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Layman: Hey dude, what's with the sad face?

Programmer: I had a programming competition this weekend, I ranked at the number 1 position...

Layman: That's great! Congrats! But why are you disappointed?

Programmer: I was aiming for the number 0 position!

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

This is what is called a signals and systems implementation (at least, that's how I call it..).

I had a similar problem a while back, when writing a piece of control software for a humanoid robot. This is actually not trivial to do correctly, as I'm sure you have figured out by now. I managed to get a decent implementation working, but it wasn't perfect (it would stall on rare occasions). My advice is to use a library for that. You didn't specify the language so I can't point you to one in particular (if you are using C++, then look at Boost.Asio or the new C++11 standard library for concurrency, especially futures and async).

I'm not an expert with this, but I can tell you how I did it. I had a class template for signals (of any type) which could be either set as synchronous or asynchronous, which meant that they would either provide the signal's value only when a new value is received, or provide the signal's value at any time when requested. Then, I would have classes that were derived from a System class. Each system object would run on its own thread, and would have a registry of input and output signal definitions (with properties like sync/async, required/optional inputs, name, type, etc.). Then, upon initialization of the structure of the software, I would connect the different systems by creating signals that acted as output of one system …

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

First of all, the field in question is computational geometry.

Then, within that field there are volumetric representations and boundary representations (or B-Rep). Most B-Reps are parametric.

There are a number of fundamental representations used for curves and surfaces (and higher order geometries). Most are based on the construction of some mathematical formula (a high-order polynomial or some piece-wise continuous patches of lower-order polynomials (splines), or some other more isoteric representations) based on a set of control-points (or knots) which are either a part of the curve/surface or just points that sort-of pulls the curve/surface in different directions but do not lie on the curve/surface. Different representations are used in different contexts because they possess different qualities (smoothness, efficiency, uniform parametrization, meaningful parametrization (e.g. cord-length parametrization), etc.).

Here are a few methods of paramount importance (you need to understand them to go any further). Most method work for curves and can be extended to surfaces, but some are specialized for surfaces.

  • Splines: This is a piece-wise interpolation between two control-points (and higher-order information like tangent vectors and normal vectors at the control points). This method is basically just a matter of solving for a polynomial of sufficient degree to ensure that the end-points match the control-points (and their higher-order vectors). For example, in first-order, you would solve for a straight-line (or plane) between two points (or three surface points), but normally you go with a higher-order interpolation (cubic or quintic). The nice thing with splines is …
TrustyTony commented: Professional help, thank you! +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If it makes sense, read it more than once and think about it differently each time.

If you read it again and again, and it doesn't allow you to think differently about it, then it is clear.
If you read it again and again, and it allows you think differently about it everytime, then it is mystical.
If you read it again and again, and it forces you each time to see it differently the next, then it is poetry.

codeorder commented: .impressed am I, for a .Clear and mystical impression, not poetry. (read that a few times xD) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Life is like a growing tree, your roots must run deep and strong, but it is only with far-reaching branches and healthy leaves that you can gather the sun-light needed to enlighten your life.

Mastication

codeorder commented: I definitely dig. :) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Are you aware that union types can have constructors, destructors, and member functions (but not virtual ones). Maybe that can help you solve your problem, which I don't quite understand.

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

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

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

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

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

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

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

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 …