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

Only an admin can win, by posting last and then closing the thread.

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

Here is a good step-by-step tutorial (for Windows XP, but I'm sure you can figure out how to do other versions too).

for the user it should look alike windows but actually performing his applications on linux platform

There are actually many versions of Linux that do look or can look very familiar to Windows users. And many windows applications can run in Wine. The KDE-based distributions (with Plasma desktop) can actually be customized to look almost identical to any version of Windows (from win95 to win7) or any version of Mac OSX, at least, on the surface (look and feel of the desktop). So, I think that what corresponds better to the description of "looks like Windows but is Linux" are one those Windows-looking Linux distributions, not Windows running in a VM inside Linux. The added bonus is that you don't have to pay for all the software that you would normally use in Windows (unless it is specialized software, most of which are also available for Linux nowadays).

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

GCC works for many many architectures, certainly including most mobile phone or smart phone architectures (mostly ARM and x86). A friend of mine compiled Ubuntu (Linux) from source for his Nokia mobile phone (not a smart phone) (and was later able to compile robot control software (C++), allowing him to control our lab's robot with his cell phone). But, that's talking about really low-level stuff (i.e., opening up the cellphone, accessing the programming bus, and flashing cross-compiled programs into its EPROM).

The main problem is that this isn't easy unless you have an "official" way to do it. And that won't be the case unless you are talking about smart phones (Android, iOS, Windows). On Android, the preferred language is Java, via the Android Software Development Kit, but it also possible to use C / C++ via a cross-compilation with GCC (targetting ARM or x86) and using the Android Native Development Kit. On iOS, the preferred language is Objective-C, but it uses Xcode and compiles to native code, and thus, C and C++ can also be used, although you should expect to have to write wrappers and things like that in Objective-C, as the entire iOS platform features won't be available directly in C / C++. For Windows systems, including Windows 8, the native and preferred development language is C++ (with C# being second), so there shouldn't be any issue there.

borland and turbo?

No. Borland / Turbo C++ compilers are not going be able to do that. …

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

Why don't you just post it here? I don't mind having an open discussion on your "changes" here. For the benefit of all, that is the spirit of a forum.

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

Hardy must be one of the most versatile and exciting actors of his generation.

Yeah, I agree too. He was really good in Warrior. And as Bane in the Dark Knight Rises. And even noticeable in his small role in Inception. I haven't seen Lawless or Bronson, but I bet he's good in those movies too. Definitely someone to watch out for. Really versatile actor.

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

Thread handling,
STL & collections,
String manipulation,
Date time manipulation, etc.

You don't even need an external library for these things. The new C++ standard (C++11) has all these features as part of the standard library. You have to get bleeding-edge compilers to use it. Otherwise, the Boost libraries provide all those functionalities and more as well:

  1. Thread handling: Use Boost.Thread or standard <thread>
  2. STL & Collections: Use the STL, with add-ons like Boost.Algorithm, Boost.Container, and many others.
  3. String manipulation: Use standard libraries like <string>, <regex>, and <algorithm>, or Boost libraries like Tokenizer, Spirit, or Regex.
  4. Date time manipulation: Use the standard <chrono> library, or Boost libraries like Chrono or Date-time.

All of the above are entirely cross-platform.

Database handling,

That's a whole different story. There are a number of different database server types and protocols, and that's really not my field, so I don't know what to recommend. Certainly, none of the above-mentioned libraries do that.

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

That's a really interesting original definition. No wonder it got twisted into meaning a cheap and miserable man. Nobody likes to be told that they are hypocrites, they prefer to say that the guy who points it out is a miserable fool.

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

What Comes First... The Chicken Or The Egg?

Eggs for breakfast. Chicken for dinner. I rest my case.

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

telnet is just one of those basic remote login methods. It is not used very much because it is not secure (not encrypted). Most remote access work is usually done using SSH (or similar secured shells). Both methods basically allow you to just login to a computer, remotely, and be able to use the "shell" (or command prompt).

In both cases, the computer receiving the connection must have a server program waiting to accept such connections. Most personal computers (i.e., not plugged to a business / academic network) will not have those programs running by default (must be installed and enabled). But if the computer is setup as an in-network computer (or workstation), these programs are usually started up very early in the start-up (since they don't require any graphics driver and user interface, which are the usual culprits of difficulties to start-up a Windows machine) because they are used for connections to log in to the campus network.

So, if you have a Windows computer that is usually plugged to a business or school network, and that seems to stall half-way through the startup, then it is reasonable to try to telnet / ssh to it and fix the problem that way. Of course, once you are logged in remotely, you still need some good know-how on the Windows system to find and fix the problem with it, with command-line access only. That's the hard part in my opinion.

If you want to "learn" to use this, you need …

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

For memory debugging purposes, you should use Valgrind. If any tool can do what you are looking for, it's Valgrind.

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

Would anyone date these 3 girls kat von d or Levy Tran or Sarah Miller?

Definitely yes. Ink is sexy (at least, those that compliment the curves). But I think dating those 3 girls at the same time would be a bit too much to handle ;)

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

There are too many to list them all, especially without a more definite idea of what you are actually looking for. The Boost libraries are probably a good first stop. For the rest, you'll have to tell us what features or particular application domain you are looking at (and RogueWave SourcePro C++ seems pretty general, like Boost).

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

"Doh!" -- Homer Simpson

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

Just ask them how they evaluated whether the programs are working or not, such that you can use that to learn what you did wrong in that code. Don't talk / whine about how it works on your end, there's no point in that, they're probably not going to be interested in taking a second look at your programs and reviewing whatever "evidence" you give them. Assume they are right (i.e., your programs don't meet the requirements), and inquire as to how they evaluated that such that you can use the same method to find the mistakes and correct.

You should also expect not to get anything, either because they don't care, or they don't want to give away the tools (or scripts) they use to verify the quality of their applications (maybe they use the same ones at every round of hiring).

My guess is probably that edge cases are the problem. The general rule with quality assurance is to test all edge cases (e.g., completely meaningless inputs, pathological cases, out-of-memory conditions, etc.). There is no point in repeatedly testing the "normal case", you test the normal cases a few times with a representative set of inputs, and then you systematically test each special case (include the "user is having an epileptic seizure" type of inputs). If I were giving job interviews for a programming job, that's probably what I would do: give them an assignment with a number of more or less difficult pitfalls or edge-cases, and then …

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

I generally prefer giving personalized answers, but your question indicates serious misunderstanding of basic concepts of class / object / variables / member / ... I think it would be better if you read this tutorial on classes, which certainly answers your question better than I could.

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

then whats the difference between using namespace and #include? doesnt #include also tells c++ to go look in this header file for this function or statement...

Not exactly. A #include line is very little more than a copy-paste instruction. It tells the compiler to look for the given file (header) and copy its content in place of the #include line. And, including a header file does not tell the compiler that any particular function or class or object will be found there. Basically, everything you include, plus every other header those included headers include makes up the sum-total of all the code that the compiler sees at one time (called a "translation unit") when compiling your code. That translation unit can be very large and contain code in many different namespaces (and sub-namespaces). To speed up the process of looking up functions and classes, and also to avoid name-clashes between them, things are split up into namespaces and addressed with their namespace (as std::cout). And the using namespace std; statement or the using std::cout; statement are just ways to momentarily avoid the full namespace qualification for every name.

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

A waste collection vehicle scenario sounds a lot like a travelling salesman problem (TSP). Or at least, like other routing problems. These are usually modeled as integer problems (or Integer Linear Programs (ILP)), or combinatorial optimization.

So here raises the question why should I use GA. How do I defense this question?

I don't know that you should. I have seen many people solving TSP using genetic algorithms. By and large, it seems that the justification is mostly that CS people all find that the TSP and GAs are both really cool things to work on, so they like to combine them. And in any given problem, the justification for using a genetic algorithm is usually this: "nothing else seems to work very well, so we'll try this." A GA can pretty much solve anything, but to get it to solve any problem effectively is an extremely long trial-and-error process and lots of fine tuning, because it is very difficult to have any kind of a precise idea of what will work better than something else. Just like its real-life analog, biological evolution: it works but takes a very long time, is very inefficient, produces wacky results, and requires enormous resources.

Here's a question for you: Did you choose to use a GA because it was good to solve this waste collection problem? Or did you choose the waste collection problem because you thought it would be a good toy-problem for testing out a GA? My …

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

But why does the video tutorial use iostream and works for him? Am I using an older version of C++?

Maybe so, maybe not. Technically, the old C++ standard (from 2003, C++03 or C++98) does not require the <iostream> header to include the <string> header, and most compilers would not do so. But, some compilers would. So, it is possible that the tutorial author used one of those compilers. Then, the new standard (from 2011, C++11) added some requirements that made it more likely that the <string> header will be included by the <iostream> header.

So, it boils down to the fact that there is no guarantee that the <string> header will be included by the <iostream> header (even if a particular compiler does it). And thus, you should always include the <string> header if you need the std::string class or anything related to it.

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

I would be in favor of a feature similar to "flag bad post" but for an edit request, for small edits like fixing formatting.

From what it sounds like, you are kinda asking for a system very similar to what is on stackoverflow (progressive moderator-powers as rep goes up, acceptance / withdrawals of edits, etc.). I don't think that really fits well on Daniweb. The idea is generally to have back and forth discussions, not the more strict Q&A format of SO.

My opinion of the specific points:

1) The person who posted can accept this edit

I think that could easily become an annoyance, especially with if you have a very inclusive population of semi-mods.

2) Other users can vote to say this edit was good

Complicates the interfaces, confuses people.

3) A moderator can accept the edit.

I guess that could be alright. Something like if you (non-mod) edit a post, it doesn't show up on the post immediately, but gets sent to the moderation channel (similar to the current "flag bad post" feature), and mods can come around and accept / reject / amend the edit. That could be useful and not too much of a burden to mods. But then again, there is a possibility of abuse if you put some button like "propose an edit" (next to "flag bad post"), then that might open too much of a flood-gate for nit-pickers and "revisionists" (there are a lot of those …

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

Yeah, that'll teach me to post off the top of my head. Consider me chassened, disciplined, served, schooled and broken.

Please don't feel that way. It was an interesting post and a good piece of code that you showed. If you want to discuss it more or have other ideas, please do so.

My post was just intended to suggest things that you might want to look into to get inspiration on improvements or applications for your idea. I didn't mean to put you off or anything, just trying to feed the discussion about an interesting topic.

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

I don't mean to burst your bubble, but this kind of thing has been around for a long while, and are used quite a bit.

Take, for example, the Boost.Property-Map library which has generic concepts for mapping keys to properties, either in the same way as you use std::map, or more general things. For example, I have in my library some data-member properties, similar to what you presented here.

Then, there are things more along the flavor of Boost.Parameter where you can give names to parameters and set them by name as you feed them to a constructor / function / setter-getter.

Funny you mention Python, because the Boost.Python library also allows you to declare a set of properties for the classes you export for a Python library.

Most plugin systems have some mechanism to created "published" properties. For example, Qt has a pretty complex property system in order to publish properties of custom widgets. COM objects have similar accomodations in their interfaces.

Then, an alternate but interesting approach that I have been exploring lately is the use of a serialization library to automatically create "schemas" for classes (e.g., like XML Schemas). I already have a protobuf schema generator (takes all the classes that exist in your program and generates a schema for them all), and one for constructing an object property tree (which I plan to use for some kind of general object-inspector + property-editor application). Since …

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

What was Einstein's definition of insanity?

"Insanity: doing the same thing over and over again and expecting different results." -- Albert Einstein

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