mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster
if ( atoi( argv[1] ) % atoi( argv[2] ) == .33333 )

You misunderstood what the remainder is. The remainder is an integer value, not a fractional value. In other words, 7 % 3 gives 1 because 3 fits two times into 7 and then there is 1 left, that's the remainder.

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

The mythbusters are awesome!... but what does that have to do with anything (unless they did an expirement with alcohol...)?

Links, which appear in underlined blue letters, can be clicked on and they will lead you to another web-page. I suggest you give it a try:
From Reverend Jim's earlier post:

Alcohol dilates the blood vessels. It may make you feel warmer but the net effect is actually to make your body lose heat faster.

<M/> commented: I should've read it :) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Do you have a question?

As for the code, there are several problems with it:

  • The header #include <iostream.h> has been deprecated for a long time, it is a pre-standard syntax that some compilers still support today, but it is not standard. The standard libraries do not have a ".h" after them, e.g., #include <iostream>. Also, for C libraries (like stdlib.h or math.h), the ".h" is omitted and they are prefixed with the letter "c" (like #include <cstdlib> or #include <cmath>).
  • The header #include <conio.h> dates back to MS-DOS and is also deprecated. Not many up-to-date compilers still provide that header, and I think that only older versions of Windows can still run it. And, of course, it's not portable.
  • The definition #define size 5 breaks the conventions used in C/C++. Definitions like these (and macros) should be in upper-case letters entirely, and should have a much more unique name than simply "size". Replace with something like #define MY_STACK_SIZE 5.
  • You cannot use just cout. You must use either std::cout or issue the following statement before using cout: using namespace std;. Your code works only because it uses the pre-standard header "iostream.h" which does not define cout inside the std namespace as prescribed by the standard. The same goes for cin, and for absolutely everything else from the standard library (including functions from C headers like <cmath> or <cstdlib>).
  • The main function should not have the signature void main(). There are only two acceptable signatures for the main function (since …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Why is there no way in C++ to ensure the safety in this case?

Why? Because C++ has an overarching principle of no overhead for what you don't use. In order to be able to do the run-time check that dynamic_cast does, the compiler has to add a hidden virtual function (or set of virtual functions) to perform this dynamically-dispatched cast operation. A virtual function requires a virtual table (per class) and a virtual table pointer (per object), and that's overhead. If the class already has at least one virtual function, that overhead is already present, and so, adding another hidden virtual function to enable the dynamic cast does not represent any overhead (per object). And that's "why" things are like they are. And also because if the compiler must put in place the facilities required to support dynamic casts on non-polymorphic classes, it must put those facilities in place for all classes (including C-style structs, which would break compatibility with C), and that would be unacceptable in terms of overall overhead (unacceptable by C++ standards, not by other people's standards, as in Java/C#).

Does it mean this above use case is flawed and that an inheritance hierarchy always needs an overriding behavior via virtual methods?

It depends what your intent is by "inheritance hierarchy". Inheritance can serve a few different purposes (and a few more purposes at the "expert level"). The main purpose of inheritance is to allow for dynamic polymorphism, and that requires a …

myk45 commented: excellent explanation! +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Convincing. I shall disregard my earlier follies and follow this fact.

Clearly, no one can deny that Orlando Ferguson was directly inspired by God when he drew that map. Such a perfect map could only have been drawn by dictation from a perfect Being with an overseen point of view on the world. Case closed.

After that, I can't believe people buy all that evil propaganda about the Global Positioning System (GPS) being based on signals from satellites orbiting the Earth. Clearly, a GPS is an Angel-detecting system that figures out your position based on your distance to the four Angels that guard the corners of the Earth! The GPS hoax is just another evil conspiracy by scientists, directly from the pits of Hell, to drive people away from the biblical truth.

God also states that guns are good

Yeah. Guns are the modern day equivalent of stoning, after all, bullets are small stones. And clearly, God loves stoning. Here's a nice way to spend a sunday afternoon: seek out anyone who is working, and "stone" them with your favorite firearm. Fun for the whole family!

He will bestow upon us the warmer climate that we deserve for our endeavours. He marvelled at our industriousness and saw that it was good.

Amen to that! Global warming is a blessing from God to reward us for doing exactly what Jesus taught us: "compete with your fellow man for resources and power", "make consumption and accumulation …

diafol commented: I nearly pissed my pants. Ha ha ha +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

All right-minded folk know that we live on a disc

That's wrong. We live on a Square and Stationary Earth.

diafol commented: I shall have to update my thinking. Square it is! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Does the word typo kinda like a iffy word.

I don't understand what you're saying. A typo is just when you mis-spell a word or skip over a word or two as you type. It is most unfortunate when the skipped over word in question is the negation (the "not" or "n't"). It has nothing to do with what is called "backpedaling", as politicians do all so often, which is to retract from a previously stated position after a storm of criticism about it (that's when you hear BS talk about "it didn't come out right", "I didn't mean to say that", or "it is unfortunate that people have interpreted my words in this offending way", and so on).

There was no such typo in my statement. Global warming, like global cooling, is a natural phenomena that occurs every so often during the Earth's history. :)

Oh well, I was just trying to save you the embarrassment of leaving people thinking you were disconnected from reality. ;) But now that you've doubled-down, I can't save you anymore... I'm sorry.

Yeah, climate changes are naturally occurring, but they don't happen by magic. Everytime they occurred before there was either a major event (e.g., massive meteor), or some major factor (usually geological or biological) that caused it. This time, that major factor is us, humans. All the evidence points to that. I don't know why I even waste time arguing about this...

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

global warming is caused by humans

Just to correct the typo, the world famous lie is:

"global warming is not caused by humans"

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

but it's kind of ugly, no? ;)

And jrd::Menu menu("A) Option A;A|a;B) Option B;B|b;Q) Quit;Q|q"); is beautiful?

I guess one could use a few MACROs too:

#define JRD_MENU_IF(MENU, X, Y) jrd::Menu MENU; MENU.addOption(X, Y, [&]() 
#define JRD_MENU_ELSE_IF(X, Y) ).addOption(X, Y, [&]() 
#define JRD_MENU_END_IF )

And then have the menu creation be like this:

    JRD_MENU_IF(menu,  "A) Option A", "A|a") {
        std::cout << "You chose option A" << std::endl;
    } JRD_MENU_ELSE_IF("B) Option B", "B|b") {
        std::cout << "You chose option B" << std::endl;
    } JRD_MENU_ELSE_IF("Q) Quit",     "Q|q") {
        std::cout << "You chose to quit" << std::endl;
        done = true;
    } JRD_MENU_END_IF;

But I guess that won't satisfy you esthetic requirements either. ;)

Joking aside, this pattern of creating the object by several calls like the addOption() function above is a bit weird-looking, but it is very useful. This pattern is predominant in libraries like Boost.Program-Options and Boost.Parameter. I also use it often for creating objects that contain many parameters and can have many options and variations, especially manufacturing objects from a class template with many optional arguments simply by returning an object of a different type at every step. For example, this version giving a static number of menu options with templated callback functors:

template <typename... Functors>
class Menu final {
public:
    // ...

    template <typename NewFunctor>
    Menu< Functors... , NewFunctor >
      addOption(const std::string& aPrompt,
                const std::string& aAlternativeMatches,
                NewFunctor aCallback) const;

    // ...
private:
    std::array< std::string, sizeof...(Functors) > prompts;
    std::array< std::vector<std::string>, sizeof...(Functors) > matches; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here is an alternative for the Menu class that might be a bit more convenient (and I guess it might qualify as a Builder pattern, not sure as I, like deceptikon, don't care too much about these things).

// menu.h
#ifndef MENU_H
#define MENU_H

#include <string>
#include <vector>
#include <functional>

namespace jrd {
    class Menu final {
    public:
        Menu& addOption(const std::string& aPrompt,
                        const std::string& aAlternativeMatches,
                        std::function< void() > aCallback);
        bool execute() const;
    private:
        struct Item {
            template <typename ForwardIter>
            Item(const std::string& aPrompt,
                 std::function< void() > aCallback,
                 ForwardIter first, ForwardIter last)
                : alt(first,last), prompt(aPrompt), callback(aCallback)
            { }

            std::vector<std::string> alt;
            std::string prompt;
            std::function< void() > callback;
        };

        std::vector<Item> _items;
    };
}

#endif

// menu.cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <regex>
#include <string>
#include <vector>
#include "menu.h"

namespace jrd {
    /*
        @description:
            Creates a menu-item from a prompt string, a formatted set of 
            alternative matches, and callback functor.

            The alternative matches string shall be in the following format:

                <match1>|<match2>...

            The prompt may not be an empty field, but the alternatives may be empty.
    */
    Menu& Menu::addOption(const std::string& aPrompt,
                          const std::string& aAlternativeMatches,
                          std::function< void() > aCallback)
    {
        std::sregex_token_iterator alt_first(aAlternativeMatches.begin(), 
                                             aAlternativeMatches.end(), 
                                             std::regex("[|]"), -1);
        std::sregex_token_iterator alt_last;
        _items.push_back(Item(aPrompt, aCallback, alt_first, alt_last));
        return *this;
    }

    /*
        @description:
            Displays the prompts for a collection of menu items and 
            executes the appropriate callback functor.

        @returns: True if a matching selection was detected, false otherwise.
    */
    bool Menu::execute() const
    {
        // Display the prompts
        for (auto x : _items)
            std::cout << x.prompt << '\n';

        std::cout << "> "; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

That's a neat code snippet!

Wouldn't it be nicer if the selection string was set to the given menu item (by name or ordinal) such that you would need to rely on the alternative match-strings for the switch case? In your test case, the alternatives are always an upper- or lower-case letter. What if you wanted alternatives like "quit" or "exit" for the quit option? That would result in two case entries (or two else-if blocks in this case).

You could have this selection-test loop:

        for (auto x : _items) {
            // Check all of the alternatives for a matching prefix
            if (std::any_of(std::begin(x.alt), std::end(x.alt), prefixed)) {
                selection = x.prompt;
                return true;
            }
        }

Then, you can do the test for selection as:

    if (!rc)
        std::cout << "Invalid selection\n";
    else {
        if( selection == "A) Option A" ) 
            std::cout << "You chose option A\n";
        else if( selection == "B) Option B" )
            std::cout << "You chose option B\n";
        else if( selection == "Q) Quit" ) {
            std::cout << "You chose to quit\n";
            done = 1;
        };
    }

I think it is desirable to make the content of selection (or whatever else identifies the option selected) have a unique value for each option, to make it more convenient and predictable for the user of the Menu class. A numeric value for the selection would also do nicely:

std::ptrdiff_t Menu::operator()() const
{
    // Display the prompts
    for (auto x : _items)
        std::cout << x.prompt << '\n'; …
tux4life commented: Nice catch. +13
deceptikon commented: I like that. +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I would find Inverted matrix A ... (A)-1

Like you would in any other language that don't have built-in methods to do so. There are many algorithms for this purpose, each with different properties (efficiency, stability, amplification of round-off errors, etc.) and for different kinds of matrices (general, normal, well-conditioned / ill-conditioned, symmetric, positive-/negative-definite, indefinite, rank-deficient (pseudo-inverse methods), etc.). By and large, however, inverting a matrix is rarely needed, so most methods are essentially methods to solve a system of linear equations (Ax = b), and by making the right-hand side equal to the identity matrix, you find the inverse (if that is really what you need). So, what you need to look for are methods to solve systems of linear equations. These include, but not limited to, Gaussian elimination (or its more sophisticated versions, the LU-decomposition or Cholesky decomposition (symmetric positive-definite)), QR decomposition (and variations like QL, RQ, and RRQR), Singular-value decomposition, etc... and the list goes on. There are entire books written on the subject, for example Golub and van Loan (this is pretty much the bible of matrix numerical methods).

There are also libraries that can do that for you, like Eigen, or my own, or the older classic (C) libraries like LAPACK or GSL.

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

Yo! I think it's chicken since God created first the mother and father of all animals that we have right now. lol hope does it make sense.

Yeah it makes as much sense as to believe that a rabbit is really popped into existence when the magician pulls it out of his hat.

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

I second that. Definitely, put that work experience on your CV. Not only does it show that you have not been sitting on behind for five years, it also shows a number of qualities like being hard working, being able to show up on time every day (at least, if your factory is anything like the wood-mill I used to work at), being consistent (the same job for 5 years), and so on.. Being a good employee has a lot in common even between wildly different occupations (programming vs. factory-floor worker, or whatever else). Work experiences should be taken out of your CV only if they are so old that they are not relevant anymore or if there is something really bad about it (very short employment, getting fired for a bad reason (as opposed to just "re-organization"), etc.).

james6754 commented: Thanks, really constructive comments. +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

how intelligent are you in dealing with those whose first language isn't English?

I have a bit of experience with that (both here and in real life), and English isn't my first language. I was lucky enough to be raised bilingual (French and Swedish), and later learned English (and use it almost exclusively every day now), and travelled around a bit and learned German (functional), Spanish (basic), Finnish (very basic), and a few things in other peripheral languages. And btw, as a result of that, I can also do accents pretty well (and suppress my own native accent easily). But one thing I can't suppress very well is my obnoxious tendency to use long and complicated sentences with lots of fancy words (that comes from French, my most native language). So, I've been around plenty on both sides of this issue, and I think I've learned to deal with that quite well.

The first thing is that it takes a bit of imagination / perspicacity to be able to interpolate, extrapolate, read-between-the-lines, and make word associations. Knowing different languages helps a lot for that because you can understand certain uses / meaning of words that would seem otherwise very odd in English but that are found in other languages (i.e., people translating literally from their native language with odd results in English). Same goes for sentence structures (e.g., speaking English with sentence structures borrowed from some other language (the speaker's native language). The same goes, of course, the …

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

Can C++11's Mutexes be used for Inter-Process Communication? In other words, can it be used for shared memory and signalling an event?

Yes. But the more important question is: Should mutexes be used for that? No. To use a mutex (or pair of mutexes) for this purpose, one could come up with a number of schemes. In any case, the scheme will be based on having one thread locking the mutex while the other waits to get a lock on it, and the unlock-lock transition would be the "signal" event. There are a number of problems with that. First, the way that a thread waits to get a lock on a mutex is generally implemented (this is OS dependent) in a loop like this:

while( check_if_mutex_is_available() )
  yield_thread_scheduled_time();

which is generally performed at the kernel level. This is rather inefficient, mostly because a mutex is not meant to be used that way. A mutex is meant to prevent two mutually exclusive codes from being executed at the same time, not as an event-based synchronization device.

The second problem are all the edge cases when the threads are running fast and are racing each other. You can have misses when thread A unlocks and re-locks the mutex without thread B noticing it (because it didn't get scheduled in between). You can have inefficiencies if thread B needlessly blocks thread A once it obtained a lock on the mutex. If you implement it with a pair of mutexes, …

rubberman commented: Great explanation of CVs Mike! +11
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I'm certain you didn't pay $10,000 USD to get it legally.

I've obtained several versions of Visual Studio "Ultimate" (or Professional) (2005, 2008, and 2010) through eAcademy and other programs that deliver free software products to university students. Most universities have such agreements (after all, it makes sense for companies to give out their software for free to students, because they'll be advocating the use of those products later when they start working).

tux4life commented: Exactly. +13
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Visual Studio 2012 (November update).

Way ahead of GCC (the other major contender) in C++11 conformance - Microsoft has implemented almost everything in the standard.

clang 3.2 with its libc++ is on par with VS 2012; and it is somewhat more mature and stable in comparison. But it has to be built from sources; and installing it is not an easy task for everyone.

Whoa... With all due respect, vijayan121, I think you are quite a ways off here. In any case, the question is not about which is the best C++11 compiler.

Overall, if any compiler is way ahead of the competition, it is the Intel compiler (ICC), it leaves the other compilers in a trail of dust with respect to code optimization and compiling speed. And the main contender to ICC is GCC, and then, a bit further behind is Clang. While the Microsoft compiler is not really competing (by their own admission), their aim is just to try and make MSVC usable, which it barely is (the "professional" alternative is to use Visual Studio IDE with the Intel compiler).

@deceptikon: The November update of MSVC11 did add support for, most notably: variadic templates, initializer-lists, and delegating constructors. This does move MSVC up to a respectable amount of support for C++11 features, about on par with the Intel compiler (in terms of C++11 feature support only). Of course, Intel is ahead on concurrency, as expected. MSVC is ahead of GCC on concurrency, which is a big …

tux4life commented: Very clear and thorough! +13
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you read the community rules, you will see the following:

  • Do post in full-sentence English
  • Do use clear and relevant titles for new articles
  • Do not write in all uppercase or use "leet", "txt" or "chatroom" speak
  • Do read the forum description to ensure it is is relevant for your posting
  • Do provide evidence of having done some work yourself if posting questions from school or work assignments

These are all the rules you have broken in this thread. Please consider them in the future.

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

Moving from Java to C++, the main thing to understand well is the distinction between Java's reference-semantics and C++'s value-semantics. Simply put, everything in Java is a reference (or placeholder, or pointer) for an object (managed by the garbage collector). In C++, everything is a value (or object, or variable) (e.g., int), which could be an address-value (pointer) (e.g., int*) or a alias for a value (reference) (e.g., int&).

Now, to the problem in your code:

class Cloneable {
  public:  // (I added 'public:', otherwise your clone() function is private).
    virtual Cloneable clone()=0;
}

There are two things to notice. First, the presence of a pure virtual function makes the class abstract, which means, in C++, that it cannot be instantiated (i.e., you cannot create an object of that class). Second, the member function clone() returns an object of type Cloneable, that is, not a reference, not a placeholder nor a pointer, but an actual object (by value). Do you see a contradiction? Such an object cannot be created because Cloneable is abstract.

Basically, to do what you want to do you have to return things by pointer:

class Cloneable{
  public:
    virtual Cloneable* clone() = 0;  // notice Cloneable* (pointer)
}

However, using a raw pointer is not really recommended for a factory function (or clone function). It is preferrable to use a smart-pointer such as std::shared_ptr or std::unique_ptr. And because std::unique_ptr is moveable into a std::shared_ptr, that is the …

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

It seems that every genius works really hard. Is it because,
(a) A genius that doesn't work hard doesn't get noticed;
(b) It's not smart to be lazy;
(c) Hard work is what makes one a genius; or,
(d) All of the above.

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

Here is a step-by-step tutorial to install Linux (Ubuntu in the tutorial) inside a VirtualBox on Windows.

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

Things like pointers and references can be called "indirections" because they are used to redirect you to another object or variable, i.e., the "pointee" or the "referee". So, when I said that all the data members become const, but only at the "first level", I really mean that the constness does not affect the target of an indirection, only the indirection itself.

I don't know of any way to explain this in clearer terms than that.

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

I think I can provide a bit more explanation. A pointer (e.g., hello) is just an ordinary variable (like an integer) that stores the address of an object. That value (the address) can be changed, like any other variable value, unless it is const. Here are a few cases:

Hello* p1;       // this is a non-const pointer to a non-const Hello object.
Hello* const p2; // this is a const pointer to a non-const Hello object.
const Hello* p3; // this is a non-const pointer to a const Hello object.

The point here is that your data member hello is declared in the same way as p1, and when inside a const member function, that data member becomes as if it was declared in the same way as p2, meaning that you cannot change the value of hello (i.e., the address that it stores), but you can affect changes to the object that it points to (i.e., as in the above, p2 still points to a non-const Hello object).

What deceptikon tried to explain is that within a const member function, all the data members become const, but only at the "first level", so to speak. An integer value becomes a const integer value. A std::string object becomes a const std::string object. A pointer becomes a const pointer. A reference remains unchanged, because references are inherently const already. But in both of the last cases, the pointee (or referee) remains of the same constness.

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

Here is the first statement explained:

[cast to non-const int pointer] ( [get a pointer to 'i' (const)] );
       const_cast<int*>         (               &i               );

Here is the second statement explained:

[cast to non-const int pointer] ( [get value of 'i'] );
       const_cast<int*>         (          i         );

The error is because an integer value is not a pointer value, and so, the const_cast cannot do that cast. It can only map pointers to pointers, or references to references.

Here is the third statement explained:

[cast to non-const int reference] ( [implicitly get a reference to 'i' (const)] );
        const_cast< int& >        (                      i                      );

Here is the second statement explained:

[cast to non-const int value] ( [get value of 'i' (const)] );
       const_cast< int >      (              i             );

The error is because the const_cast cannot be used to cast between values, only between pointers or references. For values, we talk about "conversions" not casts. As in:

int i_nc = i;  // OK: no need for const-cast since the value is copied.

A conversion is a method to copy the value of an object of one type into an object of another type. Casting operators don't make sense for that purpose.

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

Besides the inherent simplicity of the switch-case compared to else-if, there is also some performance benefit to a switch-case, at least, nominally (i.e., if the compiler is not smart enough to produce the most efficient code in either case). In the classic use of a switch-case, something like this:

enum MyEnum {
  Zero,
  One,
  Two,
  Three
};

void printCast(MyEnum value) {
  switch(value) {
    case Zero:
      std::cout << "Zero" << std::endl;
      break;
    case One:
      std::cout << "One" << std::endl;
      break;
    case Two:
      std::cout << "Two" << std::endl;
      break;
    case Three:
      std::cout << "Three" << std::endl;
      break;
  };
};

then, the switch-case is going to be more efficient because an enum is just a type-safe integer value, and the compiler will, by default, assign the values as 0, 1, 2, ... for the different entries in the enum type. When you make a switch statement like above, the code is not going to evaluate the individual conditions (i.e., (value == Zero), (value == One), ...) but will, instead, do a jump in execution based on the value of the switch variable. And that is technically more efficient. Of course, the caveat here is that even with a else-if version, it is possible that the compiler will figure out that it is equivalent to the above switch-case, and produce the same "most efficient" code anyways. But, it is one more thing to consider.

The basic lesson here is that if a switch-case statement is the more natural way of expressing something, …

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

RLE: Run-length Encoding. Generally, such encoders can be programmed as an on-the-fly mapping between input (uncompressed image pixels) and output (compressed image pixels). In this case, the encoding is best described in terms of a state machine. There are two states possible when writing pixels:

  1. Writing a sequence of uncompressed pixels (first byte < 127).
  2. Counting a sequence of compressed pixels (first byte > 127).

The state transitions are as follows:

  • Go from State-1 to State-2 whenever two consecutive pixels are the same.
  • Go from State-2 to State-1 whenever the next pixel is different from the "repeated pixel".
  • Renew State-1 whenever the number of written pixels reaches 127 (max).
  • Renew State-2 whenever the number of repeated pixels reaches 127 (max).

With that in mind, you could write the following state classes:

class TGAWriteState {
  public:
    virtual ~TGAWriteState() { };

    virtual bool writePixel(const RGB& pixel) = 0;
    virtual void writeFinished() = 0;
    virtual void init(const RGB& pixel) = 0;
    virtual void finish() = 0;
};

class TGAWriteStateU : public TGAWriteState {
  private:
    RGB lastPixel;
    std::ostream& outFile;
    std::streampos counterPos;
    unsigned char counter;
  public:
    TGAWriteStateU(std::ostream& aOutFile) : lastPixel(), outFile(aOutFile), counterPos(), counter() { };
    virtual ~TGAWriteStateU() {
      if(counterPos)
        finish();
    };

    virtual bool writePixel(const RGB& pixel) {
      if((pixel == lastPixel) && counter)
        return false; // trigger a change of the state.
      if(counter) {
        outFile.put(lastPixel.RGBA.B);
        outFile.put(lastPixel.RGBA.G);
        outFile.put(lastPixel.RGBA.R); // plus alpha channel and stuff...
      };
      ++counter;
      lastPixel = pixel;
      if(counter == 127) { // this means we have reached max, must renew state.
        finish(); …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I am planning to use a mutex for this purpose.(when the list would be altered)

That's definitely required here. You might want to check out my code snippet on lockable variables.

myk45 commented: thanks! +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Is there any problem if some shared data is accessed by multiple cores on a CPU?

Yes. There are several issues possible. Technically, if all you do, in all the threads, is to read the data, then there won't be any issues. Where things get ugly is if one thread modifies the value.

The mildest problem is that of a race condition. This is essentially a logical problem related to the fact that the output of your program depends on the relative timing between the read operations of one thread and the write operations of the other, which can be arbitrary (and non-deterministic). This can have effects ranging from a simple lag between the input and the output, to making certain input changes go unnoticed at the output, or even creating enough fluctuations at the output that it has stronger repercutions down the line (including wildly corrupt results).

Another problem is that sometimes, the write operation will be only partially accomplished when the thread is interrupted (by the OS scheduling), and if another thread reads the data at that point, it will read a completely corrupt value. This may sound like a very unlikely event, but when you are running a fast-paced loop, unlikely events become likely very quickly. This is generally solved with either a mutex (std::mutex in C++11), or atomic operations (std::atomic in C++11). A mutex is costly (blocking threads), but atomics (which are much less …

myk45 commented: thanks! +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

So... do you think should I continue to learn c++ on linux ? Or stick to windows ? I'll be writing portable code anyways.

Definitely, yes. Linux is by far preferred to Windows as a development OS. Windows is more of an impedance to development than anything else. It is not so much a matter of the quality of IDEs or of the GUI tools, but everything else, such as the stability of the ABI, the ease of installation and use of external libraries, the fixed architecture, the very rich set of unix tools (GNU), etc... Development under Windows is only preferred if you only target Windows for your applications, which is, of course, the case for a majority of people, but if you are doing cross-platform development. And this is even more true if you want to do pentesting and related development.

And what are good IDEs for linux/unix?

There is a pretty wide array of possibilities. Like many things in the world of Linux/Unix, things are fairly segmented into small tools for specific jobs, as opposed to Windows where the tradition is to spend some big bucks for some big tool that has everything. There are a number of basic tools that most IDE rely on for basic tasks. GCC is the main compiler, with Clang as one popular alternative. GDB is the debugger. Valgrind is the memory-debugger / profiler (and a whole bunch of other …

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

I'm surprise that you would date a girl that has alot of tattoos on their body. It's just I could never think that you would date a girl with a body of tattoos.
It's just not your type. The reason is you are smart guy working towards a doctorate degree, I feel you're towards girls more down to earth personality wise.

Who said anything about personality? I certainly like women with a sense of style and individuality, and if that is expressed as body tattoo, that's all the better. As for other personality traits you might associate to a women with tattoos (e.g., as certain edge or strength to her character, or preponderance to partying hard), that's a separate question, but on basic instincts alone, ink is hot.

Even if you dated a girl with a body tattoos, you might have to accepted who she is right on the spot.

And how is that different from any other woman with a strong character?

I think majority of the girls with a body tattoos does smoke.
I don't like girl who smoke.

Well, actually, I'm a smoker. And again, I'm not sure you should really infer all those traits into a person just because that person has tattoos. Saying "I like tattoos" doesn't necessarily mean "I endorse, like and support all personality and behavioral traits associated with old and generally obsolete stereotypes associated with tattoo-baring people".

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

From what you have told me, there is no real name for what I am trying to do, only names for various pieces of what I'm doing and names for other things that are similar, but not really what I want.

I'm actually more inclined to think that you don't have a very precise idea of what you want (or, at least, you are not communicating it well). The different things I mentioned all have very similar mechanisms in place to manipulate and synchronize data, except that they are each specifically tailored to very particular requirements. For example, in a version control system, you expect programmers to split up their tasks and work more or less independently and commit code to the repository every few days or weeks. With these requirements, systems like SVN or Git make a lot of sense. The example of a forum / social-network website is very different, here, the main activity is submitting new content (new entries / uploads / posts), which can be dealt with with a much simpler mechanics because concurrent new entries never conflict with each other. Both of these examples have very clear requirements about what kind of modifications are allowed, the frequency of the changes to the server's data, the work-flow (and pace) that the average user is expected to follow, etc. Solutions are tailored to the required tasks. You seem to have put a lot of focus on throwing ideas around about how you could do this …

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

@deceptikon: "I'd call such a system "stupid"."
Don't be so quick to judge, these design principles are in contradiction to the "server-client" paradigm, but they are not "stupid", in fact, they are the basis for most decentralized systems, with some notable examples like Git, Mercurial, ROS, and the Internet!

I have been struggling with the principles of creating a client-server design where the server maintains a data structure that multiple clients can view and manipulate with various restrictions on which client can access which parts of the structure. I don't know what to properly call a system like that, but on the surface it seems like a simple problem.

The most appropriate name I can think of is a Database. It is a general term, I know, but this is exactly what you are describing. And yes, as deceptikon pointed out, most of these systems are based on some centralized server that responds to request for changes to the database. If you think about it, most websites, like this forum for example, have very similar requirements: a population of users (members) with varying levels of permissions, abilities for any user to view / create / modify some of the content, keep things in-sync between multiple users viewing the same page, and also keeping things in-sync between multiple servers. These are the core operations that occur under-the-hood of most community-driven websites (Daniweb, facebook, youtube, etc.), and all these websites use one form or another of a

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

It is a shame schools are teaching with 20 year old compilers.

That's usually correlated with professors being 3 or 4 times older than that. And the last time they checked they were using the latest and greatest compiler.

I am learning C++ on Turbo C++ 3.0

Turbo C++ 3.0 is not just old, it's prehistoric. And I would not say you are "learning C++", you are learning "C++: AT&T version 2.1" which is a sort of experimental and evolving draft of C++ used by AT&T prior to making it a standard language (7 years later). Learning that version of the language has the same appeal as learning English from the turn of the first millenia: it might be interesting from a historical perspective, but not practical, except maybe for a few specialized tasks involving relics of the past (e.g., old programs, old computers, etc.).

I'll be thankful for support on Turbo C++.

It is difficult to help you in that aspect. I don't have access to this old compiler nor pre-standard reference material. So, I have no way to know what will work or not on this compiler. You'll have to start with standard code (that would work on CodeBlocks for example) and then try to resolve whatever issues come up when trying to get it to work on Turbo C++ 3.0. In this particular case, I would just try to pass by pointer:

class fish
{
     private:
         int age;

     public:
         int …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yes. /dev/sd* and /dev/hd* mean essentially the same, it just depends on your system (I think that hd* stands for an HDD connected on an IDE-bus, while sd* is for SATA or USB connected hard-drives or flash drives).

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

There also it should display one linker error since we have defined static variable inside .h file.

No. There is a certain allowance for static const data members which is similar to the allowance for inline functions (functions defined in the header file either within a class declaration or marked as inline). For static const data members of primitive types (e.g., integers), it is allowed to define them in the header file even if that would technically lead to One Definition Rule (ODR) violations, because for such primitive types and under the assumption that all instances of those data members seen by the linker came from the same header file, it is safe to assume that they will all be equal. And because they are constant, there is no problem in having many copies (or optimizing them away entirely), but if non-const, then there must be a guarantee of a single instance being manipulated. And because they are of primitive types (with trivial constructors), there are no issues of side-effects from the multiple construction of the static data member (in multiple translation units), but if non-primitive, then there must be a guarantee that the construction happens only once during the static initialization. So, obviously, this exceptional rule doesn't apply to static data members that are non-const and/or non-primitive (class type), in which case, they must be defined in one translation unit only (one compiled cpp file).

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

Well, there is a huge difference between the two. Try compiling this:

Foo(true, 2, 5.0, "dude");
Meh(true, 2, 5.0, "dude");

Meh requires that all parameters have the same type (or, at least, all be convertible to the type of the first argument). That's not the case for the Foo version, which can allow the parameters to be of completely unrelated types.

Basically, this is like comparing std::tuple and std::array. Of course, if all the types are the same (or it is acceptable to convert them all to one type), then you should use std::array or analogously, Meh from your example. However, if you don't want to impose that restriction, then you'll have to use std::tuple and/or variadic templates (as Foo from your example).

What's the pros and cons of using Foo vs. Meh? Are there downsides?

They solve different problems. Foo is more general than Meh. Using Foo to solve a problem that Meh can solve is overkill. That's about it. Well, except for the fact that the syntax of Foo is really annoying, believe me, I know.

Does one have an overhead?

No. Everything will be inlined and unrolled equally well in both cases, no overhead. For very large sequences, Meh might be more cache-effective.

Which do you prefer?

The one that solves the problem at hand.

triumphost commented: :o definitely didn't notice that Meh had restrictions :) Thanks A LOT! +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The operations in addbook() (saving in file) and the operation in display() (loading from file) are not the inverse of each other, and thus, the loading will fail. Here is what I mean, say you have the following values for your variables:

string bookname = "C++ Primer";
string publisher = "Addison-Wesley Professional";
string author = "Stanley B. Lippman, Josée Lajoie, Barbara E. Moo";
int copies = 42;
int price = 45;
int edition = 5;

After you run the following code:

input << bookname << publisher << author << copies << price << edition;

The file will contain the following:

C++ PrimerAddison-Wesley ProfessionalStanley B. Lippman, Josée Lajoie, Barbara E. Moo42455

At this point, there is no way to extract the information back from the file because it is all jumbled up. You are going to need separators to mark where each field begins and where they end. One such marker is simply a new-line. If you output the data to the file in this format:

input << bookname << endl
      << publisher << endl 
      << author << endl
      << copies << endl
      << price << endl
      << edition << endl;

it will be a lot easier because the content of the file will now be:

C++ Primer
Addison-Wesley Professional
Stanley B. Lippman, Josée Lajoie, Barbara E. Moo
42
45
5

which is a lot easier to load, simply reading it line-by-line (see std::getline()).

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

I wish I saw that this thread earlier, because I knew the issue right away when I saw "clock()" in your code. The clock() function basically returns the number of clock ticks consumed by your program (overall process). Because each core has its own ticking clock, well, if you have one thread running on one core and another running on another core, since both threads belong to the same process, the "clock ticks" counter for the process is the addition of the time spent on both cores. In other words, your initial test program was doomed to only produce nearly equal times with slightly higher times for the threaded version because of the overhead of creating all those threads.

To keep track of time, you need to use a "real" time function, such as time(), std::system_clock, std::high_resolution_clock, or Boost.Date-Time.

If you have 4 cores, you should expect the time to be 4 times less. (from ~27s to ~8s seems reasonable)

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

How to find which operating system is running the PC in C++?

Well, C++ is a compiled language, meaning that a particular operating system is always targeted when compiling the code, i.e., the operating system type is known at compile-time. And all compilers will define a number of predefined MACROs that will identify (fairly completely) what the target system is. Here is an example of using that:

 #if defined(_WIN32)

   // this is a Windows environment!

 #elif defined(__linux__)

   // this is a Linux environment! (any GNU/Linux distribution)

 #elif defined(__APPLE__)

   // this is a Mac OSX environment!

 #elif defined(BSD)

   // this is a BSD environment! (OpenBSD, FreeBSD, etc.)

 #elif defined(__QNX__)

   // this is a QNX environment!

 #endif

You can find a comprehensive list of predefined macros here.

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

Here's a little house, a Sun, and a mid-day drunk:

       \ | /                                 (
      -- O --                                 )
       / | \                                 (
                                              )
                                            |__|____
                                           /        \
                                          /__________\
                      o                   |   _      |
                    --|--                 |  |_| ||  |
                      |\                  |      ||  |
LastMitch commented: Wow, this is nice 3 drawings. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Easiest/Safest option: Reinstall Linux on the entire system, overwriting WinXP partitions. If you can fairly easily take a backup of all your files (e.g., take a backup of /home folder) and put those files on a separate partition (non-windows, non-linux) or on a separate hard-drive (external HDD or pen-drive), then it is probably easier to re-install Linux by re-partitioning in such a way to eliminate all the Windows and current Linux related partitions, and replace them with a fresh installation. Then, you can copy the /home folder back and reinstall all the software (you can use dpkg --get-selections and dpkg --set-selections to get a complete list of installed software, and then re-install all the software from that list, that's the perfect way to restore the entire set of software when creating a fresh install). Linux makes it so easy to create a fresh install, that this is probably the easiest thing to do.

If a fresh install is not an option, then you can fix-up the dual boot into a single boot Linux. First, you have to take care of the bootloader. If you are using Grub as the main bootloader (first bootloader), then you'll have nothing to do at this step. If you are using the windows bootloader (i.e., meaning that you first see the windows-bootloader, and then you see the Grub menu (with multiple kernel versions to choose from)), then you will probably want to remove the Windows bootloader and install Grub on the MBR, such …

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

NULL is just zero for pointers. In actuality, there is no difference in the value. It is merely a convention that you should set and test pointers with NULL, and use 0 for integral type (int, short, etc.). On many compilers, NULL is just a #define for 0. In newer compilers, you should technically use std::nullptr instead of NULL, but it is still gonna be indifferentiable from 0. There is, in fact, a section of the standard that mandates that the two (literal value 0 and NULL or std::nullptr) have the same value (all bits zero).

So, just respect the convention and stick with using NULL or std::nullptr for pointer types, and using 0 for integral types. Things are just clearer that way.

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

You should create the thread object when you want it to start. And the join() function is basically to wait for the thread to finish (i.e., join the thread with the current thread). If you want the thread to start when j is equal to 25 and then finish it at the end, you can do this:

int main()
{
    thread t1;   // default-construction means "no thread".

    for (int j = 0; j < 50; j++) {
        if (j == 25)
            t1 = thread(f1);   // create (start) and move a thread into 't1'.
        cout << j << endl;
        Sleep(500);
    }

    t1.join();

    cin.get();
}
thendrluca commented: this is what i searching for :) thx +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Oh yeah, sorry, this should work:

mel[i].assign(&temp[melstart[i]], &temp[melstart[i]] + mellength[i]);

notice the & to take the address of the values in temp.

phorce commented: Great help - Thank you very much :) +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Shouldn't it be melstart[i] and not melstart[0]?

Also, you should use the reserve() function instead of resize if you are going to use assign() after, that will avoid the default-construction of all the objects that resize() would trigger. So, I guess this should work:

      mel[i].reserve(mellength[i]);
      mel[i].assign(temp[melstart[i]], temp[melstart[i]] + mellength[i]);

Also, I don't think that you need the temporary array temp. Why not just use mel[i] directly?

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

The std::set container is a sorted container which means that it will not allow you to modify the elements that it contains, because that could break the ordering. This means that set iterators will only give you const references to the elements of the set, i.e., (*it) is a const reference to a vector of ints. And a const-vector can only provide const-iterators to its elements. And the error you got is a result of trying to assign a const-iterator to an non-const iterator (it2). This should work:

std::set<std::vector<int>,Compare>::iterator it;

  for( it = combinations.begin(); it != combinations.end(); it++ ) {

    std::vector<int>::const_iterator it2;   // notice the 'const_iterator' here.
    for ( it2 = it->begin(); it2 != it->end(); ++it2 ){
      std::cout << *it2 << std::endl;
    }
  }
TheBrick commented: Excellent! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To your previous problem, I don't really know what is going on. But I would generally recommend that you don't use only one file-stream for reading and writing. I think that is where the problems might be coming from. Generally, you should use a ofstream for output operations, and ifstream for the input operations. You probably should go about it something like this:

  • Keep all the records (dInfo) in a vector.
  • When asked to save all the records to a file, then,

    • Open the file using a ofstream, with flags ios::binary | ios::out.
    • Write the entire vector of records into the file.
  • When asekd to load all the records from a file, then,

    • Open the file using a ifstream, with flags ios::binary | ios::in.
    • Clear the current vector of records (or keep it temporarily).
    • Read all the records from the file into a vector.
    • (Merge the vector of records from the file with the pre-existing record vector, eliminating duplicates).

That's going to be easier the manage. Then, all your other operations can be done on that vector of records (not through constantly reading and writing to a file). Also, using the input-stream for inputs and the output-stream for outputs will give you a better chance at avoiding the issues you have with the end-of-file marker and stuff.

It's got the period between dInfo and push_back underlined and is saying:

If you look at the reference website for push_back(), you'll see that, …

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

The solution to your problem is to use dynamic loading of the DLL. Look at the functions: LoadLibrary(), GetProcAddress(), and FreeLibrary(). This is basically the way that you can programmatically call a function (LoadLibrary) to load the DLL, then make calls to the GetProcAddress function to obtain function pointers to individual functions within the DLL, and then, once you are completely finished using the DLL, you can call FreeLibrary to un-load the DLL. This is, of course, a lot more trouble than doing it statically (the traditional way, where it gets loaded before you even start the main() function) because you have to manually assign all the function pointers via calls to GetProcAddress.

Another solution is to create a module of your own (a DLL) that has all the code that uses that DLL, but exposes fewer functions. Then, that new module would load the DLL in question statically (as usual), but be loaded dynamically by your main application. This way, you avoid having to dynamically load the external DLL, if that DLL has a lot of functions to be loaded from it, and you can still catch the error about the missing DLL.

N.B.: Under Unix/Linux/MacOSX systems, the equivalent functions to LoadLibrary / GetProcAddress / FreeLibrary are dlopen() / dlsym() / dlclose(), respectively.

Can you please explain what is /MT and how to enabled it ?

The /MT is a command-line option for the MSVC (microsoft visual C++) compiler …

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

Chop your own wood, it'll warm you twice.
-- Henry Ford