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

They are smart only in planting and growing opium poppy.

@Xantipius: They have a choice between growing opium poppy in the hopes of earning a decent living, and growing a normal food crop which they won't be able to sell at a price that can compete with subsidized crops from wealthier nations, meaning they'll run out of money and be forced to sell their land, probably to people willing to grow opium on it. It doesn't take a genius to figure that out... I guess thinking isn't really your department.

They appear as poor (they are but the media makes it worst) but a lot of them are rich people. The rate you find millionares in afghanistan would be more common in america (based off of population).

@<M/>: That's the irony with poverty and wealth, they usually go hand in hand. What every poor country has in common is a population of obscenely rich people. Here, in Quebec, we have many very rich people who immigrate here out of very poor African countries (old French colonial countries), either permanently or for their college studies. This is just the tip of the iceberg. Most of these poor countries function with a massive population of poor people who work hard and ear very little, then some foreign corporation that is sucking them dry, but you always have a strata of local millionaires who work either as the cogs of the corrupt government or as local pawns for the …

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

But we really thought that we brought into this country the kindess and socialism.
Then it will turn out they need NO our help and services.
They want make heroine only. Nothing more. They are stupid animals.

I suggest you study history a bit more carefully than that before making bigoted statements like that.

The two biggest periods of growth of opium cultivation in Afghanistan were during the Soviet occupation and, now, under the US occupation. There was an opportunity for the Soviet government to make a lot of money by taxing the opium growers for the money they made from selling their opium in Russia (through Kazakhstan). Basically, they figured they couldn't stop the trade so might as well invade the place, make the trade an interior business, and collect estate taxes from the opium growers. They went in and highly encouraged more farmers to grow opium, and got the Russians addicted to heroin by a massive inslot of inexpensive merchandise, especially in Novokuznetsk and other cities bordering Kazakhstan. It's a good way to scrape every last penny from your people's pockets (whatever they had left or managed to hide from the USSR government).

When the Afghans were left alone, they made modest efforts to reduce the production, and eventually the Taliban took more drastic measures and reduced the production by nearly 90%. Of course, when the US came in, pretty much the first thing they did was to reinstate the opium production to meet …

<M/> commented: Another good post from a poster I respect +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

He can download the Open Source version that Some Guy wrote, install the compiler, check the settings and build it, or, he can buy the Windows version for £9.99 and it does what he wants, near enough.

Most of open-source Linux software can be downloaded and installed from the repositories in a single click (or a single command on terminal). In my experience, it is far easier to install most open-source software in Linux than in any other OS. Even free software in Windows is annyoing to install (download the installer, run it, click "next" about a doxen times, wait for an incredibly long period of time, and then, possibly restart), and I'm not even talking about the stuff you need to buy at a store or pay-download-validate online. Where do you think the idea of having "app stores" came from? It's a direct copy of the software distribution model that has been used in Linux for ages.

Linux is too complicated and whilst we techies might like that, the average computer user can barely figure out that the internet isn't a program on their computer (Okay that's very sweeping generalisation but I'm sure you get my point).

There's been a lot of progress in that department. If you use a main-stream distro like Ubuntu, Mint, Fedora, OpenSUSE, Android or Google Chrome OS, there's not much that is "too complicated" about it, although if it isn't pre-installed, it does require a bit of tech-savvy or you …

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

I was in Baltic Sea just a few years ago (maybe 10 years ago) on a USA flag fising factory ship doing some work for the company I worked for. We were about 200 miles from Alaska shore, no one mentioned mines in the water. Perhaps they are just on the Russian side of the sea???

That doesn't make any sense. How can you be in the Baltic Sea and within 200 miles from Alaska's shore? I think you're confusing the Baltic Sea with the Bering Sea.

Ancient Dragon commented: You are right +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Nomatter who you are or who she was, everyone should give the dead respect.

There is a fine line between respecting the departed for the sake of their family and loved ones, and creating an unfairly glorified picture of a person just because they passed away. At any point in the last decade, you could have asked me what I thought about Thatcher and I would probably say her policies were absolutely terrible and destructive for the UK, and that she was probably one of the worst prime ministers to take office. And now that she passed away, am I supposed to have a different opinion? No, my answer is the same.

I couldn't care less that she passed away, I didn't know her personally, and her death doesn't affect me in any way. However, because she passed away, she's in the news and people are talking about her more than usual. And because of that, people with unflattering opinions of her will express those opinions more than they usually do just because they're talking about her more than usual. This is not "dancing on her grave". It's just honest people giving their honest opinion, which hasn't changed just because she died, why would it?

I much prefer that kind of honesty to people who try to somehow cobble together a massive silver lining and say only nice things out of "respect" (either don't say anything or give your honest opinion), or even worse, those who use this …

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

Overall, I'd have to say Unix. It's the basis for virtually all the main operating systems used today. It's architecture has stood the test of time. Apple's operating systems were always somewhat based on Unix and have now (with OS X / iOS) crawled back home to the Unix family (POSIX-compliant). Even Microsoft has finally made modest moves in that direction (e.g., getting a bash-like shell with PowerShell, and adopting a more Unix-like user-privilege system), i.e., kind of retro-fitting some Unix-inspired elements. And, of course, GNU/Linux and BSDs are essentially (open-source) implementations of Unix, and now dominate every market (servers, clusters, embedded systems, phones, tablets, routers, DVRs, etc.) with the exception of laptop/desktop PCs.

I know that this is a bit of a cop-out, like answering "what is the best car" by saying "the internal combustion engine car" (which is includes virtually every car built in the last century), when clearly the question asks for the best car brand and/or model. But I like to say Unix, because it has the benefit of, for once, putting Microsoft alone in a corner with no friends, and once you frame it as Windows vs. Unix-family-and-friends, there's no competition.

I guess you should narrow down what you mean by "best operating system". If a discussion (or flame war) is to occur, you would probably need to narrow things down to "highest quality personal computer operating system", otherwise, being inclusive, there isn't much debate to have, except maybe between GNU/Linux and BSDs.

So, I …

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

I was thinking of using sockets. Thread A prints and sends a message to thread B. Thread B prints and then sends a message to thread A. Any thread before printing checks for the message from other thread and prints only if they have received the message.

You have the right idea, but the wrong channel of communication. Communicating thread notifications through a socket is terrible from a performance point of view. All operating systems or multi-threading frameworks will provide a number of different types of thread synchronization mechanism to do this kind of thing. There are a number of approaches that could solve your problem. One solution is a condition variable which basically allows one thread to notify another of a condition. Another is a synchronization barrier which allows two threads to have a "meeting point" that both must reach before any one of them can continue. You could probably also solve your problem with a pair of mutex locks, but be wary of dead-locks. For faster operations, you can also use atomic operations on volatile flags. I think that's enough food for thoughts.

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

How Can I Restricted The Movement Of The Cursor And Determined At Which Point/Pixel User Hit Any Key..!!

As you record the key-strokes to move the cursor, first check that the movement is allowed (remain within the ranges of x and y values), and, of course, keep track of the coordinates of the cursor, you can use those coordinate values when you get the "hit any key". Please show your code if you want more detailed explanation.

Graphics In C++ Are Much More Difficult As Compared With Python, Java, C#...!!

The difficulty mainly comes from the fact that graphic user interface libraries are not part of the standard library in C++ (as they are with some other languages). Being primarily a general-purpose system infrastructure programming language, having a GUI library in its standard library would be a really bad idea. However, there are many external libraries that can be used in C++ for this purpose, most of which are just as easy to use as in other languages, in fact most of the GUI tools of other languages are written in C++ with a thin layer that give you access to them.

Is There Any Way To Learn About C++ Graphics Within 3-4 Weeks That Are Enough For This Game..!!

It would seem to me like basic console graphics is probably enough for this game. The thing is, what you can do in the console is quite limited, so I guess you want to …

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

Categorizing C++ as an OOP language is very reductionary. C++ is a multi-paradigm language. C++ was originally motivated by the OOP "revolution", and that played a major part in its original popularity. In modern times though (21st century), the popularity of C++ is mostly driven by what Alexandrescu calls "zero-overhead abstractions", or as Stroustrup puts it "an uncompromising infrastructure language". In other words, C++ is remarkably effective at allowing you to create high-level abstractions with minimal overhead, that is, you don't have to make compromises on the performance in order to construct the kind of complex software designs that are needed in certain complex applications. In large part, this is because it allows you to move very freely between the simple-yet-effective procedural programming style (i.e., C-style POD-types and free functions), the dynamically-flexible object-oriented style, and the highly customizable, zero-runtime-overhead generic programming styles (i.e., the STL), and blend them all at your heart's content.

Today, "competing" languages are sort of stuck in the niche that they dug themselves into. Of course, some high-level languages like Python do not pretend to compete with C++, but rather embrace the complementary role that they can play (i.e., providing simple-to-digest and flexible wrappers for what is mostly C / C++ code running under-the-hood). But others, particularly Java, are pretending to compete with C++, especially in the field of infrastructure programming. They generally rely on arguments of being less complex / easier to learn, on providing more flexibility, runtime safety and portability, and on the idea …

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

First of all, only non-static member functions can be declared as const. The const-ness applies to the object on which the member function is called, that is, the object and thus all the data members it contains. Here is an example:

class Foo {
  public:
    int bar;

    void member_func() const;
};

void free_func(const Foo& f);

void Foo::member_func() const {
  bar = 42;   // ERROR: data-member 'bar' cannot be modified, it is part of a const object.
};

void free_func(const Foo& f) {
  f.bar = 42; // ERROR: data-member 'bar' cannot be modified, it is part of a const object.
};

int main() {
  Foo f;
  f.member_func();  // calling 'member_func' on the object 'f'
  free_func(f);     // calling 'free_func' on the object 'f'
};

So what is the difference between making the agrument constant and making the function itself constant?

As you see from the above example, nothing is different. Qualifying the member function as const is just the way to tell that the first hidden argument to the function (which is the object on which the member function is called) must be treated as const within the function.

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

Oh what a tangled web we weave,
When first we practise to deceive!

-- Sir Walter Scott

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

I would like to find out why is it not necessary for a method to declare an exception when coding in C++?

Actually, now with C++11 (latest standard), it is more than just "not necessary", it's deprecated (compilers must still accept the code, but it's highly discouraged to use explicit exception specification in your code). This is essentially a case of "lots of pain but no gain".

Specifying the exceptions that can be thrown by a function can't really accomplish much beyond just causing a hard crash if an unspecified exception is ever thrown. And because the whole thing is a dynamic mechanism (run-time), there is a run-time overhead to it and no benefit in static code optimization (like in the case of noexcept where the exception-handling code can be removed entirely) which is where traditional "native" languages like C++ shine. So, that was the "no gain" part.

In Java, since it sits at a higher level, it can have checked exceptions and can actually optimize accordingly (although modern exception implementations don't benefit from this), and the run-time overhead is eliminated by resolving this at compile-time. If C++ wanted to do the same, it would have to get further removed from native linking formats (e.g., ELF) and would have to specify at least some, if not all, binary interfaces (ABI) which it currently does not (and that is a huge move to make, and a widely debated and argued topic too). One of the advantage of designing a …

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

The O() means "of the order of". Generally, a function is of the order of its biggest term, i.e., the term that, as n becomes very big, dominates all the others, in other words, the only term that really matters for large values of n. So, if f1(n) = A*n + B*n^2, then it is of order n^2, so you would say that f1 is O(n^2), i.e., g1(n) = n^2. So, just think of g1 as "the largest term of" f1. If the function is now f3(n) = f1(n) / f2(n), then the corresponding g3(n) should be the largest term of f3(n). The question asks to demonstrate that the largest term of f3 is not going to be g1 / g2, i.e., the largest term of (f1 / f2) is not equal to the largest term of f1 divided by the largest term of f2. It is a rather straight-forward demonstration to make.

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

Jim: But to be honest, most of what I say is not worthy of scrutiny.
..
ddanbe: But as in real live I'm not going to look for weapons, illegal drugs etc., I'm surely not going to do that on the web. So as far as me is concerned, everything I've put on the web may be seen by everybody.

I always feel a bit queezy when I hear what is essentially the "it's OK cause I have nothing to hide" argument. Why do people have opaque walls to their houses, why do they put up curtains, why do they surround their property with a fence or bushes, if they truly consider that it is OK for other people to know everything that they do, since they got nothing to hide. I think that equating the need for privacy with the desire to hide your criminal activities is a false equivication.

First, it generally makes the assumption that the only reason why anyone might look into your private business is to discover criminal activity. The reason there are warrants is because the law is structured as: if you want to look into someone's private business to discover criminal activity you suspect, then get a warrant, if you have any other reason to look into someone's private business and you do so, be prepared to go to jail. That's how the "it's OK cause I have nothing to hide" perspective is resolved by the law and how …

GrimJack commented: I'm with you on this -it drives me crazy +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I was just roaming the internet for some interesting reads and I came across this very interesting paper about how to define a legal framework for the "reasonable expectation of privacy" when it comes to our new cyber-existence. I thought I'd share it with you guys, and see what you think about agencies being able and allowed to collect and analyse huge amounts of data about any individual they like.

The main point of the article is that the conventional wisdom that says that when you roam outside, in public places, you can't expect privacy (i.e., people (incl. authorities) could be watching what you do) doesn't work when it comes to roaming the cyber-world (visiting sites, blogging, chatting, posting on forums / leaving comments / tweeting, etc.) because, in that world, people can collect and analyse all of your actions (past and present) as a whole and this way, they can infer so much about who you are, what you do, who you associate with, what your views are, etc..., that it amounts to things that anyone would consider to be their "private business". And in most countries, private citizens (and by extension, companies) are not allowed to look into other people's "private business" too much (i.e., it's illegal, and usually a felony), and authorities are not allowed to do that either unless they can show "probable cause" and obtain a warrant.

Currently, many agencies and private companies are taking huge liberties in this regard, enjoying the legal …

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

AFAIK "rank" cannot be bought. It must be earned.

I wish that could apply to politics too.

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

Why anyone praise SCIENCE before GOD?

I praise science because it's awesome (even though careless fools can use it to do bad things).
I don't praise God because there isn't a shred of evidence of that such a being exists. I don't worship Santa Claus either.

Why anyone praise SCIENCE before GOD?

Well if science is just another part of God's "wonderful creation", then get on-board with the plan and concentrate your efforts on science, don't waste time praising God, He probably would prefer to see you getting busy fulfilling His plan for the fruition of science.

Praising science has a practical purpose, i.e., to promote it and encourage people to learn about it, to develop their critical thinking, and participate to the advancement of society, the last 3-4 centuries have been the most fruitful, lets keep it up!

Praising God has the effect of lending credence to many of the corrupt leaders that lead the "flock", those who twist some vague old scriptures into any meaning that serves them. Praising God reinforces the idea that it's good to believe in things without evidence, leaving the door wide open to charlatans and propagandists. Praising God sends the message to your fellow humans that you do not care to work with them, to discuss with them, to reason with them, and to compromise with them for a better world for all, but that you'd rather blindly obey some rigid cosmic law very incompetently handed down by …

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

I don't mind that there are lots of "inferior" programmers, in the sense that their knowledge is limited to being able to push the right buttons here and there to get the job done without much understanding of either the technical details or the theoretical aspects of things. I don't mind that because we need a lot of those people, after all, the bulk of all the software being developed worldwide is absolutely trivial to write (e.g., mobile apps, web-pages, etc.), I mean, trivial in the sense that it doesn't require deep technical know-how or fancy out-of-this-world algorithms.

The problem is, whether you're interested in learning to push buttons for a living, or in learning the deep technical know-how, or in creating the next fancy out-of-this-world algorithms, what do you do? You enroll in a CS degree. This is unsustainable. It creates introduction-to-everything curriculums that try to mix all of these things into one, and the people who graduate from those CS degrees are led to believe that they are now experts at all these things when they are at best a novice at one of them (and they often have an attitude, big talkers, little doers). And as Schol-R-LEA said, the people who actually turn out to be really brilliant are those who went out of their way to really learn the subject, and they often have a lot of trouble getting that recognized as they are stuck in a crowd of average button-pushing programmers with basically the same …

deltascrow commented: Yup. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

:'( but how will i live without him ? he is my heart ! to whom can i tell my feelings ? my parents are also so impatient. his ambitions, care, love , he himself i gonna miss.

I'm sad to hear that. I think you ought to tell him about what you just said there. I had a feeling from your original post that this was more of a cry of pain than anything else. Your grand pa will live on in the memories you share and in the things he inspired in you. Cherish every moment you have left with him, but don't be afraid, everything's gonna be alright. Talk to him about it, after all, I'm sure he has faced plenty of deaths of loved ones in his own life.

@imBaCodes:

Its not no one was looking for a cure . Its Because that illness does not exist in the past centuries.
Why do we have this desease nowadays? its because of Science noot all things discovered by science

You really must be joking, or insane. It's true that many illnesses did not exist in past centuries, that is, when life-expectancy was around 25-30 years old. Since medical science (mostly germ theory, hygiene, vaccines, and penicillin), life-expectancy has almost tripled. Many of the old-age illnesses didn't exist because very few people made it to that age, and those that did, died of "old age" or "natural death" which are just umbrella terms …

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

The language standard and the standard library is developed as a negociation between implementors (who need to comply to it) and users (who want features from it). If the amount of users that request a particular feature very strong and all implementors have little or no problem providing it (they often provide it already, just not in a standardized way), then it can go into the standard.

In this case, there isn't much need for unbuffered streams. Any kind of serious reading / writing operations involving files (or, equivalently, cin / cout) will need to be buffered. And there are only very rare occasions (mostly "toy" console programs) where an unbuffered input would be useful (mostly in making the program nicer, but usually not critical to its operation).

Then, how can you specify that the stream should be unbuffered? There are always buffers everywhere. There are usually hardware-cache chips at both ends of a SATA connection, there is buffering done by the operating system on most file I/O operations (and terminal / console I/O is usually implemented via files, or virtual files), and heck, there is also multiple levels of caching (L1, L2, L3) between RAM and the CPU. In this kind of environment, what is "unbuffered"?

Do you mean that there isn't buffering done in user-space (e.g., under the hood of iostream or printf/scanf)? But that still doesn't eliminate the buffering done in kernel-space, in the CPU architecture and at the hardware level. So, even if the standard had …

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

When I grew up, in the school yard, we used to play soccer only during the winter. The summer was for basketball, kickball, dodgeball, and street hockey, and the winter was for hockey, soccer and football.

Playing soccer in winter time (and outside) is pretty nice actually, I don't know why it isn't more popular. And I certainly don't see any problem with playing under a light snow-fall as shown in the linked video, just like they do for football. It's certainly nicer than playing in the rain, and with very little risk of lightning, making it even safer. As for slipping, it's no worse than a wet pitch.

Whoever schedule this game should be kick in the A88.

I don't think you can blame the guy who scheduled the game several months in advance for not being able to make a weather forecast that even the biggest super-computers in the world aren't able to do. And when the snow came, for the reasons mentioned above, I see no reason to cancel the game.

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

I was reading some book and the author for some reason said that classes just store pointers to the location of all datamembers

That's the way it is in reference-semantics languages like Java or C#. This is not true for C++ (which has value-semantics), either the author is not talking about C++ or he knows nothing about C++. In reference-semantics languages, the stack doesn't exist (abstracted away) and automatic variables don't exist either. All memory is managed by a virtual machine, so, it's all essentially heap-allocated memory, and each data member is also individually heap-allocated, and there's an extra indirection (reference) to everything you do (although sophisticated virtual machines try to optimize away some indirections and some heap-allocations). This fundamental difference leads to completely different styles of programming, so, be very careful about mixing books / personal-knowledge of Java/C# with C++, it's a bit like trying to learn to do snowboarding by taking skiing classes (or vice versa), they are kind of similar and knowing one helps for learning the other, but if you try to face forward (as you would while skiing) while on a snowboard, all you'll do is fall on your face. If you are transitioning from Java to C++, keep that in mind, and don't blame the shape of the snowboard for your falls, just learn to ride it in the direction it's meant to go.

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

Can functions even be on the heap?

Functions do not occupy any memory on a per-object basis, only the data members. Functions are made up of executable code and occupy memory on the code-section of the program's memory. They exist in one place for the whole program, and require zero memory per object. And no, they cannot be on the heap, even if you tried, you cannot have executable code in the freestore (as far as I know, and any attempt to do so is definitely a very unusual hack).

I understood the class is on the heap by why are all the data-members on the heap too if they are not allocated with new?

I think you seem a bit confused about what the difference between the stack and the heap is. You seem to think of those two things as sort of the same thing (free-store), which is incorrect, so let me just spell that out to make sure the foundation is solid.

The stack is a static chunk of memory that is given to the program (at startup) to allow it to create local (automatic) variables within functions. We generally say that the stack grows as functions get called (entered) and shrinks when they return, which is a pretty accurate way to picture it. Think of the stack as a large static array (usually between 1Mb and 8Mb), and you start with a pointer sptr to the start of that array. You enter …

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

First, a bit of vocabulary. Given a class, an object of that class will contain data members and base-class objects (the instance of its base-classes), these two things are referred to as sub-objects.

So, the fundamental thing to understand here is that, from a memory perspective, an object and the collection of all its sub-objects are one and the same thing. So, if you have this simple class:

struct Class1 {
  int a;
  int b;
};

Then, an object of class Class1 has two sub-objects, i.e., two integers. In memory, an object of class Class1 is two integers. If the object is on the stack, it is two integers on the stack. If it is on the heap (free-store), it is two integers on the heap.

As for the Foo class, then, in memory, an object of that class is a std::string. If the Foo object is on the stack, so are all its sub-objects, because they are one and the same. Sub-objects are just the sub-divisions of the memory that the object occupies. So, sub-objects always reside in the same memory (stack vs. heap) as the object they are a part of.

It's that simple. There is no indirection here. When you access a data member of an object, you are not being redirected somewhere else in memory, you are merely accessing a specific part within that object. This is one of the crucial aspects of value-semantics. In reference-semantics languages (like Java/C# and many others), everything is …

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

Writing a GUI application in C++ must involve one of many GUI libraries out there. As Tinnin mentioned, some possibilities are SFML or SDL, and in that same vein there is the Win32 API. All these options are very low-level. They can be useful for making a computer game where the window is basically just a window with a 2D/3D display.

If you want a more complete GUI, with menus, buttons, list-views, etc.., you need a more elaborate GUI library. One of the front-runners and most used library and toolset for this is Qt. This library is very complete, well-designed, and easy to use. And it works on all platforms. Another lesser popular alternative is WxWidget.

In the Microsoft world, they have pretty much given up on providing a modern C++ GUI library, you have to move to .NET in order to use WinForms. Technically, you could use C++/CLI which is a hybrid between C++ and C#, but I wouldn't recommend it, if you want to do .NET, just use C# (which, in a nutshell, is almost identical to Java).

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

The CSV format just means Comma-Separated Values. A typical CSV file would look like this:

x, x2, x3
1.0, 1.0, 1.0,
2.0, 4.0, 8.0,
3.0, 9.0, 27.0
4.0, 16.0, 64.0

It's that simple. Just the values, separated with commas. Excel can also import any other similar thing, like values separated by spaces or tabs. Here's some simple code to generate a CSV:

<fstream>

int main() {
  std::ofstream file_out("my_test.csv");

  file_out << "x, x2, x3" << std:endl;
  for(double x = 1.0; x < 10.1; x += 1.0)
    file_out << x << ", " << (x * x) << ", " << (x * x * x) << std::endl;

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

since we are software engineering students at the University of Waterloo in first year we are still learning all the tedious linked list implementations

Keep in mind that linked-lists are theoretically nice and make for good prorgramming exercises in computer science classes, but they are far from being all that useful in practice. Cases where a linked-list is the better choice are few and far between. Can't use them if you want random-access. Shouldn't use them if you want to do frequent traversals. Shouldn't use them if you need to sort the data, or keep it sorted, or do searches. An array of pointers is almost always preferrable to a linked-list if the objects are expensive to copy (and cannot be moved, which is very rare) and/or you need them to have a persistent address in memory, and the array-of-pointers comes with the added bonus of less overhead and random-access capability.

This leaves you with very few application areas, most of which end up requiring a hybrid structure (e.g., unrolled linked-list, linked-arrays, cache-oblivious lists, etc., or with an efficient small-object allocator), or have the data distributed over modules or computer-nodes in a linked topology, or in a medium where data mobility is very difficult (e.g., a file-system). The argument also extends to other kinds of linked-structures (linked-trees, adjacency-list graphs, etc.), although in many cases the alternatives are not as easy or convenient to implement and don't pay off as much. But for everyday simple tasks (for which you …

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

I already created a version that just stored numbers as "before decimal point [unsigned array]" and "after decimal point [unsigned array]".

The decimal point? That's untenable. Are you saying that in order to store the number 1e30 or 1e-30 you need to store a long array of zeros followed by 1? That's insane. You should look at the way the floating point numbers are stored for real, and emulate that to arbitrary precision (instead of fixed). Where the decimal point falls is completely arbitrary, and has no baring on the precision nor the storage requirement.

Second, I must assume that you're doing base-2 arithmetic. Base-2 arithmetic is what the computer understands and work with well. So, I assume you mean "decimal" just in a colloquial sense, not in the sense that you use base-10 arithmetic. Don't work against what is natural for the processor.

The issue is that it is both inefficient and incomplete.

Yeah, that's gonna be a problem. Doing this is really hard, see the GMP and MPFR libraries.

I would like to incorporate complex numbers into the system (I am not, however going to incorporate quartic numbers). I am also going to incorporate vectors and matrices.

That shouldn't be a problem at all. Once you have a good arbitrary precision class, with all the required operator overloads and standard function overloads (sin, tan, log, exp, ldexp, frexp, etc...), you should be able to use std::complex

ddanbe commented: Deep knowledge. +14
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This discussion might enlighten you. You find this behavior strange, but understand that the inverse behavior could lead to results just as strange, if not stranger, considering that it would go against the more general scoping rules in C++. There are maintainability issues with allowing functions in the base-class to overload those of derived classes. That's a general maintainability rule, things in a broader more general scope should not change the behavior of code in a narrower sub-scope. This is why local variables take precedence over global variables of the same name, the same goes between namespace scopes, and between derived and base class scopes.

Think about this. Say you're part of a team of developers working on some big library / application. Your job is to work on class "Derived", and some other developer that you barely know works on class "DeepBase" which is somewhere a few inheritance levels up from the class you're working on. One day, that developer pushes a small change to the DeepBase class' code, the next day you wake up with the team screaming at you because the code in the Derived class broke the last nightly build. Now, you're stuck plowing through the code to find the source of the problem, and then, after a lot of pain-staking research and debugging, you realize that a call to a function of the Derived class was being re-routed (through overloading) to a newly added function in the DeepBase class. This is a maintenance …

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

I guess the endorsement system can't keep up with the rate at which your "friends" in California register phony accounts and endorse you (i.e., most of your endorsements are from people from California, who registered in the last month, and barely posted anything themselves). You're not exactly coming to this issue with clean hands, are you?

This may be irrelevant but i also noticed that i recieved reps from a user who had 7 rep points and my rep points didn't go up

I guess you're speaking of this post and the rep by this user. 7 rep-points is really low (and coincidently, the 7 reps you gave him), and it also depends on other factors (post count, time since registration, etc.), that's why this user (from Calfornia, registered 2 hours ago...) has the "Power to Affect Someone's Reputation Positively" of 0.

I don't know what you're doing or what you're hoping for, but it sure doesn't smell very good.

tux4life commented: So true. Last I checked some accounts were even unverified. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is not a bug, it is the expected behaviour. There is a rule in C++ that overloading of member functions is limited to a single class scope. Basically, calling SomeFunction on a Derived object causes the compiler to look for overloads within the Derived class only. If I compile your code with Clang (which has superior warning messages compared to GCC), I get the following messages:

overload_inheritance_test.cpp:13:10: warning: 'Derived::SomeFunction' hides overloaded virtual function [-Woverloaded-virtual]
    bool SomeFunction(const int& A, int& B) const { return false; }
         ^
overload_inheritance_test.cpp:6:18: note: hidden overloaded virtual function 'Base::SomeFunction' declared here
    virtual bool SomeFunction(const int& A) const = 0;
                 ^
overload_inheritance_test.cpp:24:43: error: too few arguments to function call, expected 2, have 1
    std::cout << "Hey: " << SomeFunction(5) << std::endl;
                            ~~~~~~~~~~~~  ^
overload_inheritance_test.cpp:13:5: note: 'SomeFunction' declared here
    bool SomeFunction(const int& A, int& B) const { return false; }
    ^

The error is the same as GCC (unresolved overload), as expected from any standard-compliant compiler, but what is of interest here is the warning preceding it. That basically sums it up, any function in a derived class with the same names as a function in the base-class will hide that base-class function from overload-resolution, which can be useful in some circumstances, but is mostly annoying. I don't really know what the reason is for this rule, but I imagine it has some technical ramifications, otherwise the standard committee wouldn't have imposed it.

The way to fix it is to use the using statement, as …

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

First impression, it seems right to me

I beg to differ.

Computer Systems Technology – Networking

You should write "Computer Systems Technology and Networking" (without quote marks), the dash is confusing, it looks like a separation between propositions (in the grammatical sense) and breaks the flow of the sentence. Making a major grammatical blunder is not a great way to start a cover letter.

I am a student at St. Clair College studying Computer Systems Technology and Networking looking for a student job as a Network Administrator Assistant.

You should avoid using the same word three times in one sentence. You're a "student", we get it. Also, the word "student job" is not really appropriate, maybe "internship", "employment", "experience in the workplace", etc... For example, consider this re-phrasing:

"As a student in Computer Systems Technology and Networking at St. Clair College, I am eager to gain experience in the workplace."

Or, a bit more forward:

"As a student in Computer Systems Technology and Networking at St. Clair College, I believe I am ready for a challenging internship in a high-standard company. For that reason, I immediately considered Bell Canada and ..."

My interest in working with Bell Canada lead me to the Jobs@Bell website, I noticed Bell Canada offers an internship placement in network technology and IT that I am interested in pursuing.

Be selective about the information you put in a cover letter, you only have a few sentences on average …

Mike Askew commented: Sound advice / comments +0
tux4life commented: Great advice :) +0
ddanbe commented: Great post and 42! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As Jim said, you must see the CPU as an interpreter of machine instructions. It takes in instructions and executes the required actions. In order to have stability over time, it is most practical to have a standard set of instructions that all CPUs (or a class of CPUs) can be made to understand / respond to. Those standard sets of instructions are called Instruction Set Architectures, or usually just "instruction sets". Familiar instruction sets include x86, x86-64, ARM, AVR, PowerPC, and many extensions like SIMD (SSE, SSE2, SSE3..). And many instruction sets are compatible (mostly backward compatible) to provide more stability. Most PC CPUs today will implement either x86 (32bit) or x86-64 (64bit), plus many SIMD extensions. Then, GPUs might support even more SIMD-like extensions (btw, SIMD is for doing many floating-point operations in parallel, which is very useful for 3d graphics). Most other less common instruction sets are for embedded devices or very big computers (servers or super-computers), due to the special needs these environments have.

The instruction set is essentially the language you need for talking to a processor. It is a very simple language, as in, every individual instruction is kind of trivial. It goes a bit like this:

Take the number 2
Take the number 3
Add them together
Give me that number
Now take the number 4
Multiply them together
Keep the result
Multiply again
Give me that number

which would probably execute roughly this code:

int c = 2 + 3;
int …
Reverend Jim commented: Much better explanation. +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The dynamic allocation is unnecessary (and leaking), you could simply do this:

int i = 0;
for (i; i < n; i++) {

    Neutron neutron;
    initNeutron(&neutron);

    int steps = 0;
    do {
        fprintf(file, "%f\t%f\n", neutron.r[0], neutron.r[1]); 
        ++steps;
    } while (step_succeeded(&neutron));

    fprintf(file,"\n");
    step_sum += steps;

    if (neutron.absorbed)
        ++absorbed;
    if (neutron.escaped)
        ++escaped;
}

Another problem is that you translated this line of C++ code:

r = vector<double>(2, 0);

into these lines of C code:

this->r[0] = 2;
this->r[1] = 0;

You misinterpreted what the C++ code meant. The vector was being constructed with the second version of the constructors, see here, which takes the length of the vector as first argument (2) and then, the value with which to fill the vector (0). This means, the C code should be:

this->r[0] = 0;
this->r[1] = 0;

Then, another big issue is with the random number generator. In the C++ code, you have this line:

double theta = 2 * pi * rg.rand();

which takes a random number in the range [0,1] (produced by rg.rand()) and multiplies it with 2-pi in order to get a random angle between 0 and 2-pi. In your C code, you have:

double theta = 2 * pi * rand();

which might look like the exact same thing to the untrained eye, but they are entirely different. The C rand() function generates a random integer number between 0 and RAND_MAX (which is usually a …

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

Is there good and bad type of compiler? or wording of the question is incorrect!

Good / bad is too vague, it depends too much on what you want: faster code, faster compilations, wider platform support, better value for your money, better debugging tools, stability, standard compliance, etc...

The main C++ compilers are GCC (open-source from GNU), ICC (proprietary from Intel), MSVC (proprietary (but free) from Microsoft), and Clang/LLVM (open-source from Apple and Google and others). There are also a few others like C++Builder (Borland -> Embarcerado) and IBM's XL compiler. Each of them have different qualities and marketing points. Also, most are split between front-end (that parses the code) and back-end (that generates the executable code), and those can be crossed (e.g., GCC front-end with LLVM back-end, or Clang front-end with GCC backend, or EDG front-end with ICC back-end). And then, there are the standard library implementations, which are mainly the GNU implementation (libstdc++), the LLVM implementation (libc++), and the Dinkumware implementation (proprietary) (used by Microsoft, IBM, Borland, Comeau, and many others).

A broad-brush classification, in my opinion and limited knowledge, would be this: (X > Y: X is better than Y)

Faster code:
ICC >> GCC > Clang > MSVC

Faster compilation:
MSVC > Clang > ICC > GCC

Wider platform support:
GCC > ICC > Clang >>> MSVC

Debugging tools:
ICC > MSVC >> GCC = Clang

Stability:
ICC > GCC >> Clang > MSVC

Standard compliance:
GCC > …

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

As the titles says I wanna know what are versions of C++ other than Standard C++ and what are the differents between those version if any!

The first "version" has to be the ARM (around 1990-1991). This wasn't an official, formal standard document, but the later editions were essentially the working draft for the standard in 1998. This pre-98 version of C++ is what is generally referred to as "pre-standard C++". The language changed quite a bit from 1985 to 1998, so it cannot be defined in clear terms what exactly was or wasn't in it. It basically goes a bit like this. The core addition to C from the start was classes, that is, the extension of C-style "struct" to include member functions, inheritance, the private/public/protected scopes, and all those kinds of classic object-oriented programming features, and probably also things like const, references, function overloading, etc., the things that weren't part of C but were well established in other new languages of the time. Then, during the 90s, the more exciting stuff was introduced, such as exceptions, templates, namespaces, and, of course, the main components of the standard library that we could hardly live without today, like STL containers and algorithms, and the IO-stream library. Another noticeable difference between standard and pre-standard C++ is the fact that pre-standard headers had the .h extension (as in #include <iostream.h> or <math.h>, as opposed to today's <iostream> and <cmath>), and the elements (classes and functions) of the standard library were …

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

There are a few observations that I must make before saying anything else.

First of all, your Control class is a resource-holding class, and should be designed as such. So far, your class is ill-conceived if it is to be holding a resource (i.e., tied to an active window). You have to ask some fundamental questions like: Should the class be copyable? Should the class be moveable? Or neither?

Second, the dynamic polymorphism that you are trying to imbue on the Control/Button classes seems very awkward to me. Seems to me like a clear case of not observing the golden rule of OOP inheritance: "Inherit, not to reuse, but to be reused". I see two telltale signs: (1) your Control class seems to want to serve two purposes, be a base-class with some set of virtual functions and be a provider of some basic functionality in being the care-taker of a window-resource; and, (2) the inheritance is not oriented towards polymorphic services being provided but rather implementation details being shared (e.g., the "Dispose()" function). The main focus of an OOP inheritance scheme should be to establish (through the base classes) a hierarchical set of functionality provided by the descendants (derived classes), if a few innocuous data members (directly tied to functionality) show up in the base classes, it's no big deal, the same goes for a few helper (protected) member functions. But these commonly useful data members or member functions should never be the reason for the inheritance …

bguild commented: Excellent effort and completeness +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I will use "malloc" to reserve a space for the ErrLog structure and assign the pointer value same as the char array. Is this ok or just use vector?

If you're going to use dynamically allocated memory to store your error logs, then you'd be better off using an STL container like vector or list. That's for sure. I was assuming you wanted to avoid dynamically allocating memory during the formation of the error log, due to the fact that it creates stochastic and long latency between the formation of the error log and being able to catch it or respond to it. In embedded systems, this is often a requirement when hard-real-time constraints exist. If you don't have such constraints, then you definitely should consider using C++ exceptions which will be far more convenient and faster than that error-log scheme. By creating polymorphic exceptions, the whole problem of determining what you should include in your error-log struct will go away, since you can create custom exception classes for any given situation with whatever data members are needed for that specific situation.

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

I have some idea on the member and would like to get some suggestion to add / optimize the data structure :

One thing certainly pops to mind, include a pointer to the next error log. The reason for this is not for a linked-list linking, but that it is often the case that you want to catch an error which causes the broader function to fail and forward a broader error log out for that function, which then causes its caller to fail, etc... In other words, you want to nest the errors such that you can trace back the errors from top to bottom. It is really annoying when an error pops up from the depth of the code without any idea of the stack-trace behind it (from where and for what reason was that deep function called and failed).

So that, every module reporting the error log and store in a data structure directly instead of keep return a false from function.

Since you are posting this in the C++ forum, I must ask why you can't use exceptions? I know that embedded folks are not big fans of C++ exceptions and prefer lighter-weight alternatives (which lead to smaller code and deterministically short latency, but also produces slower code). In any case, the mechanism you are proposing is heavier, less flexible and slower than C++ exceptions, so you might consider using them instead of developing your own custom error reporting mechanism. But, of …

tux4life commented: Great advice Mike :) +13
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think we largely agree on this topic. When I look at your example C code, I see a generalized effort to keep variables as locally scoped as possible, within bounds of reason. It's style is in complete agreement with the guideline, at least, the way I see it, which I think is essentially the same as you. Code like the one you linked to (formatted I/O, parsing, etc.) does require things like tentative variables, flags, lots of switch-case style coding, etc. In this realm, the paradigm of "here are the variables I'm playing with, and here is the code" is a natural one, but even then, you still show evidence of trying to limit the scope, which just proves my point.

I don't know what you think I mean by declaring variables where they are first needed. That C code obeys that guideline, in my book. What I see are things like:

  1. Declare a few variables that will store the results of a loop.
  2. Run the loop (with locally declared variables that are needed only per-iteration).
  3. Inspect / return the result based on those variables.

So, those variables that appear at the start of the loops (which I presume is what you are pointing to, since all other variables in that code are declared directly on-site of where they are needed) are being declared and used at exactly the time and scope at which they are needed.

I'm not advocating for an obsessive compulsion to declare variables at …

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

declare your variables as close as possible to where you first use them

That's debatable.

Well, I don't mean that you should give the death penalty to those who don't follow that guideline. It's a very minor offense to good style. In other words, it's good to foster the habit of declaring variables as locally as possible, but I don't mean that you should go back and refactor all your code to bring it on par with that guideline.

And if you want to debate the issue, take it up with Herb Sutter, Andrei Alexandrescu and Bjarne Stroustrup. Not that I wouldn't have arguments of my own on that subject, but they've made better cases for this guideline in the past than I could.

don't create variables with uninitialized values

Also debatable.

Ditto.

"Antiquated" isn't synonymous with "bad",

Yeah, that's exactly why I used the word "antiquated" and not the word "bad". I meant antiquated in the sense that it is a relic of the past, an outdated practice. I guess you could say it's one kind of "bad", but I prefer the more precise term "antiquated" because it conveys what I mean. If you want to argue that antiquated isn't necessarily bad, well, maybe not always, but I didn't say "bad", so you're barking at the wrong tree.

It's an outdated practice because it came from the earlier days of programming when stack-growth limitations (i.e., when they can occur) …

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

Do you have a specific question?

Otherwise, here are a few remarks on your code:

  • You are using pre-standard headers like <iostream.h> and <math.h>. These shouldn't be used today (as in, not since 15 years ago). You should use <iostream> and <cmath> (all C++ standard headers don't have the .h, and all those taken from C (like math.h, stdlib.h, stdio.h, etc.) also omit the .h and are prefixed with the letter c).
  • The conio.h header is not standard and is certainly not guaranteed to be supported anywhere, although some popular C++ compilers in Windows do support it still today. There is no reason to use it here.
  • Since standardization, all standard library elements (classes, functions, objects ..) are in the std namespace. This means that accessing cout for example should be done by either writing std::cout everywhere you use it, or writing the line using std::cout; in the scope in which you are going to use it, or writing the line using namespace std; in the scope in which you are using cout and other standard library components.
  • The main() function is required to return an integer value. The two acceptable, standard forms for the main() function is either int main() { /* ..*/ }; or int main(int argc, char** argv) { /* .. */ };. The return value should be 0 if the program executed correctly, and something else otherwise.
  • Your formatting of the code is quite ugly. Indentation is important, and spacing out the code is too. In …
deceptikon commented: Nice. +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

What about a filtered iterator?

Here is what I mean:

template <typename BaseIterator, typename OutputType>
struct ActorIteratorImpl {
  public:
    // the set of required typedefs:
    typedef ActorIteratorImpl<BaseIterator,OutputType> self;
    typedef OutputType* value_type;
    typedef OutputType* const & reference;
    typedef typename std::iterator_traits<BaseIterator>::difference_type difference_type;
    typedef OutputType* const * pointer;
    typedef input_iterator_tag iterator_category;

  private:
    ActorFlag required_flag; 

    BaseIterator cur_it;
    BaseIterator end_it;

    // this function seeks the next valid base-iterator
    void seekValidIterator() {
      while(cur_it != end_it) {
        OutputType* tmp_ptr = dynamic_cast<OutputType*>( *cur_it );
        if((tmp_ptr) && (tmp_ptr->hasFlag( required_flag )))
          break;
        ++cur_it;
      };
    };

  public:

    // constructor (not to be called directly by user).
    ActorIteratorImpl(ActorFlag aRequiredFlag, BaseIterator aCurrentIter, BaseIterator aEndIter) :
                      required_flag(aRequiredFlag), cur_it(aCurrentIter), end_it(aEndIter) {
      seekValidIterator();
    };
    ActorIteratorImpl() : required_flag(), cur_it(), end_it() { };

    // define an equal operator for the base-iterator:
    friend bool operator==(const self& lhs, BaseIterator rhs) { return (lhs.cur_it == rhs); };
    friend bool operator==(BaseIterator lhs, const self& rhs) { return (lhs == lhs.cur_it); };
    friend bool operator!=(const self& lhs, BaseIterator rhs) { return (lhs.cur_it != rhs); };
    friend bool operator!=(BaseIterator lhs, const self& rhs) { return (lhs != lhs.cur_it); };

    // then, the standard iterator operations:
    self& operator++() {
      ++cur_it;
      seekValidIterator();
      return *this;
    };
    self operator++(int) {
      self result(*this);
      ++(*this);
      return result;
    };

    friend bool operator==(const self& lhs, const self& rhs) { return (lhs.cur_it == rhs.cur_it); };
    friend bool operator!=(const self& lhs, const self& rhs) { return (lhs.cur_it != rhs.cur_it); };

    value_type operator*() const {
      return dynamic_cast<value_type>(*cur_it);
    };
    value_type operator->() const {
      return dynamic_cast<value_type>(*cur_it);
    };

};

Note that you could fairly easily make …

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

Because you're humble, and would never brag about how awesome you are...

Why do cars have four wheels?

TnTinMN commented: mine has 5 wheels +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

"I always wanted to kick a duck up the arse." -- Karl Pilkington

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

i've been looking more into kd-trees and they all use pointers to parent nodes which is what i thought a linked list was...

Well, Kd-trees are, first and foremost, trees. So, yes, they are naturally expressed as linked-list-style structure: each node has a parent pointer and a few (2 or more) pointers to children nodes (with the exception of the root (no parent) and the leafs (no children)). But take this with a grain of salt. When you read descriptions of the structure or the algorithms (insertion / deletion, etc.), they will often assume this kind of linked-structure, and you will probably also see that in example implementations (or pseudo-code). That doesn't mean that it should be implemented exactly in that way. There are many ways to actually implement a tree structure (especially with fixed branching factors), and a linked-structure (i.e. pointers to parent-children) is usually the worst way to do it, but it is also the easiest to use in pseudo-code / examples. Unfortunately, some (or many) are misled into thinking that the pseudo-code or the explanation of the algorithm / data-structure actually corresponds directly to how it is implemented in real life. In this domain, these types of explanation must be regarded more as if someone told you "it has a metal frame, two wheels, a set of pedals, and a handle bar" as a way to instruct you on how to build a bicycle. In other words, there are lots of additional implementation details and …

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

the linked list would point to what's above, below, left, right, previous and next, with this it would be i think fairly easy to move objects around inside the map by jumping from node to node.

Linked-lists perform extremely bad for any kind of traversals. It might seem "easy" to move from node to node, but easy doesn't mean efficient. There are ways to implement a linked-list for efficient traversals, but that's also really hard and rarely worth the trouble.

for computer and player controlled objects i was thinking of just dividing there location by the size of each block globally and locally to get the position though i'm not sure of the computation overhead from a lot of division operations.

This is basically what a Kd-tree is, or similarly, an Octree / Quadtree. A simple solution that could be a good start would be to do a coarse Kd-tree partitioning, i.e., recursively divide the space only up to some coarse resolution, and store an array of objects inside each area. That would make the array of object in local areas quite small, meaning that dealing with them is easy and quick. And because the final division is coarse (not too small in volume), objects won't tend to transfer from one area to another too often, reducing the amount of maintenance to do (remove an object from one area and insert it in another). This certainly won't be optimal or anything like that, but it will …

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

This sounds like a space partitioning tree. I'm guessing it has something to do with collision detection. In any case, as rubberman said, this is far from being a trivial problem in which picking an STL container is not sufficient (you need something much more elaborate than what the STL can provide off-the-shelf), and, in addition, picking a correct storage strategy (within a more elaborate space partitioning tree) will not be a trivial task either.

The main concept that you must get acquainted with is the concept of "locality of reference" (aka "memory locality"). This is what can make or break a space partitioning structure (and, more generally, any search tree structure). The idea is as follows: the memory accessing patterns that characterize your main tasks (e.g., look-up, nearest-neighbor, etc.) must map well to your underlying storage such that traversals are reasonably sequential and operations are reasonably localized in physical memory. The point is that if you randomly jump back and forth in memory, you are maximizing the amount of cache misses, which, in turn, completely dominates the performance (or lack thereof) because one cache miss is roughly equivalent to a couple of hundred clock cycles (instructions). For example, if every distance computation (between a query point and a node of the search tree) takes about 20 instructions to compute, then having a cache miss at every new node visited is going to make the performance about 10 to 20 times worse than what you could get with …

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

However, I'm wondering if this type of response is actually counter productive with regard to the ultimate goal of this site which is to generate revenue.

It definitely is counter productive. I don't know much about search engine algorithms but I would certainly imagine that they try very actively to filter out any sites that are just link relays. At least, some years ago I remember it was much worse when you did a search and half of the pages coming up were other search-like sites or phony forums with links (or not) to other sites, often not any better, and so on, until you eventually found some original content. Now, this is a thing of the past. I imagine there are strong rejection criteria for sites that seem to act only as a hopp to other links, given traffic analysis of those sites. That's why the market of such sites (attract traffic with links, make money with adds) seem to be disappearing (no longer attract traffic due to SE filtering them out), which is a very good thing and promotes original content.

The problem with questions that could simply be googled is that there is no good way to answer them. If you leave it unanswered or simply say "just google it", then that will be frustrating to anyone finding this discussion from google, they will come and go really quickly and that will work against search-ranking of Daniweb. If you give some short answer with some …

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

I notice that add() got broken in your changes. It just traverses the (probably nonexistent) path rather than adding keys where they don't exist. You'd end up dereferencing null pointers unless new nodes are added at the right places:

Yes you're right. I originally re-wrote the code with a by-value storage of the nodes, in a std::map<T,node>. Until I realized that it wasn't standard-compliant to assume that an incomplete type could be stored in an STL container, although many implementation allow it (because it is certainly possible to implement STL containers that allow incomplete types, but the standard doesn't require it). So, I went back and changed it to unique_ptr, with rather ugly effects, including that bug, which wouldn't have been one if the nodes were stored by value. I guess this is a legitimate case for wanting containers to contain incomplete types, it would save one level of indirection and one level of new-allocated memory, both of which are a big deal in a tight loop.

Btw, you, again, introduced three map lookups where only one is needed:

template <typename String>
void add(const String& s) {
    auto it = &root;
    // Traverse the path and extend it as necessary
    for (auto c : s) {
        // lookup / create the node for the character c:
        it = &( (*it)->link[c] );
        if (!(*it)) {
            // it didn't exist yet, so, create it:
            (*it) = std::unique_ptr(new node());
        }
    }
    (*it)->terminal = true;
}

For this class, …