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

There is no way to generate a true random number from a computer program. Random number generators that most programming language libraries have are actually what is more precisely referred to as "pseudo-random number generators". They simply use some math functions that are very wild (in reality, these math functions are very tricky to define because you need them to produce "wild" numbers, but you also need those numbers to be uniformly distributed over a certain range). In any case, those numbers are deterministic and predictable, even if they don't look to like it.

To produce truly random numbers, you generally need some hardware that taps into some external, naturally-occuring, random process. These are called hardware random number generators and most modern computer chipsets have such a device such that they can operate cryptography and other things that benefit from having truly random numbers (e.g., not predictable by an attacker that is trying to break the security). Many programming languages also provide standard functions to access that random device, such as std::random_device in C++.

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

Why is Daniweb's mascot a dude

Because, like in any healthy household, the woman is the queen and the man is the puppet.

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

And Miley Cyrus can make a comeback to disney as a tongue-flailing, crazed, twerking, naked, alien... no makeup required.

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

Will this work?

Yes. However, notice that there is a difference between that program and your original one. In the original program, if there is not enough memory (bad-alloc exception) to store all the numbers, the program will not read any number at all. In the second version, the program will read numbers up to the maximum that it can read before it runs out of memory (if it ever runs out of memory). That could make a difference if you expect the amount of data to be large enough to exhaust the memory available. For example, if you are running this within a multi-threaded application, the second version could exhaust the memory and cause a bad-alloc problem in a concurrent thread, where you might not expect such an exception to occur (and thus, not have the try-catch blocks to handle it).

The while(!in.eof()) loop is within the try-block. Is this okay? Or should the try-block be within the while loop? Does it matter?

It is better to put the try block outside the while loop, as you did. The reason why it matters might not be obvious at first, but it's an interesting one. In general, with loops, you want to keep the inside of the loop as short as possible because this is code that gets repeated over and over again. If the code for a single iteration can fit within a cache page, then the entire loop can run over and over again …

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

In that example, the vals array would be called a static array or fixed-size array. But, the tests that are done in the get and put functions would be called "bound-checking" or bounded array access (I.e., the array access is "bounded"). So this might explain how you got the term "bounded array" from.

Hiroshe commented: you beat me too it +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As far as I know, the term "bounded array" is not really standard terminology for anything in particular. I would assume, however, that it refers to a static array, something like this: int arr[5];. It is still used today, for sure. When you just want a small set of objects or variables for the duration of a function, or as a data member of a class. However, technically-speaking, the C++11 standard introduced the std::array class template which can replace a static array and has a number of benefits, such as being copyable, and usable like an STL container.

What confuses you about static arrays?

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

Are you using some external library? Anything other than the standard libraries? If so, verify that the libraries you are linking to have been built with the same version of MinGW (or close to it) as the one you are using. This "dw2" version of this DLL is an obsolete file newer versions don't use (and don't install), but if an external library that you use is built to still be using it, you'll get this kind of errors.

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

In view of the latest head-butting between Linus Torvalds (head of Linux) and Kay Sievers (head of Systemd), this looks to be related. Apparently, systemd has had a long history of ignoring bugs and forcing others to work around their quirky or sub-standard software. The fact that it doesn't strictly filter logs seems to be inline with that reputation. I would assume that in any seriously maintained software projects, such trivial vulnerabilities would be patched up (up-stream and down) as soon as it's discovered.

I recently went through the exercise of compiling the Linux kernel from source for a ARM board. Systemd was one of those components that was constantly giving problems along the way, but in all fairness, it's pretty central too. This project should be handle with double the rigor of any other project, but instead, it seems to get about half the rigor of other projects.

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

But I can blame them for the choice of characters as it didn't have to be Padme. The whole Padme thing seemed poorly thought out to me.

I don't think that the choice of Padme as the "lucky lady" was inherently bad. After the first of the prequel movies (The Phantom Menace), they had a decent setup to work with (at least, on paper). They did need a high-profile female, they did need it to be a romance (What else? .. A one-night stand?), and it also made sense to have the seed of the affection planted before any Jedi training. So, overall, they were in a decent position (plot-wise) at that point.

It's really on the second movie that they missed the mark completely. They clearly had no inspiration on how to make that romance happen in a believable way; it felt like the kind of romantic fantasy that a pre-teen with a crush would make up (e.g., something will force us to be together somehow, then we'll play and laugh together, and we'll be in love, and then we'll kiss on the lips!). It's the least imaginative and most forced way to create a romance. It was just really lazy on their part.

And in the third prequel movie, they just had to build on the terrible foundation of the previous one, but mainly they had really terrible dialogue and acting between the two characters. The dialogues in that movie should go down as some of …

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

1)Trying to explain the force.

I agree that some things are just better left unexplained. I think that fans love the Force as just this mystical force that gives some awesome powers. The fans think "If the Force existed, it would be awesome!", and the only explanations that are needed is to explain exactly how awesome it is (i.e., like Yoda's training of Luke), but not where it comes from or how it could be worked around the rules of physics or whatever.. that's just part of the suspension of disbelief.

2)Shoehorning a romance in the unlikeliest of places.

Well, the problem is that they needed to create this very critical romance between Anakin and Padme in order to get Luke and Leia conceived. So, you can't blaim them for putting that one romance in the prequels. However, you can blaim them for doing a really bad job at it. Since romance is so hard to get right, they should have planned it out better and given more efforts writing, acting and directing those scenes.

The only reason that the Leia / Han romance worked pretty well in the original series is because it just came out naturally from the chemistry of the actors, the contrast between the characters, and the well-written dialogue between them.

3)Comedy relief character(s) that only pissed us off.

I think that if it was only about George Lucas, then entire movie would be a comedy for children. There's been …

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

The 880M card has been added pretty recently (last May) to the officially supported list from the Nvidia Linux driver version 331.67. This is pretty much the latest stable Nvidia driver (there are a couple of later Beta drivers). So, assuming you can install this driver, i.e., that you have either the know-how to install it manually or that your distribution of Linux is recent enough to offer it in its repositories of proprietary drivers, then it should work fine. Needless to say, such a cutting-edge graphics card will require such a cutting-edge (recent) driver, and such a recent driver will, in general, require a fairly recent kernel version, meaning that you should pick a cutting-edge distribution of Linux, such as Arch or just a very recent version of Ubuntu or OpenSUSE or whatever... The Nvidia site doesn't give a minimum for the required kernel version, but I would aim to get at least 3.10 or later, which most newest releases of Linux use (OpenSUSE is 3.11, Ubuntu is 3.13, and with Arch you would probably get 3.15-16 now (rolling), etc.).

N.B.: The Nouveau driver's team maintains a list of cards supported by their drivers. Your card (GTX 880M) is not yet listed there. I would assume that it won't take too long for the 800-series to be supported, as they already support the complete GTX 7xxM series and everything below it. I would say probably a couple of months. But in any case, you can just use …

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

Thanks Moschops for that shout out. I was just going to point to that stack overflow answer.

Choosing a good STL container for a given situation is a pretty subtle task, unless it's a trivial problem. I would generally recommend writing your code in a generic way to be able to swap the container type without too much trouble, then use the one that seems the most appropriate (it's usually vector), and test different containers if this code seems to be a bottleneck in your software.

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

Hey guys,

I just wanted to give a shout out for the McGill Robotics team. This is a team of undergraduate students from different engineering disciplines here at McGill. They are participating to the RoboSub competition right now! They managed to build and code a fully operational, autonomous submarine robot in less than a year, very impressive.

I'm a fan of that team in part because they are the reincarnation of the McGill LunarEx team, which is a robotics team that me and my friend founded back in 2008, and kept going with new students since then, until the Lunar excavation challenge was abandonned in favor of this new and challenging competition. Several of the students in the team have also been working in my lab. I've also been involved, at arms length, with some of their work. I also gave them a crash-course in C++ programming when they were getting started using C++ and ROS for their control software.

If you want to see what robotics is all about, check out the videos on their youtube channel, or check their website. You can also follow their progress live on twitter @McGillRobotics.

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

Try to put the full path instead of just the file name, to see if this is a problem of file-path (maybe the system function runs the command in a different directory then that of the program?).

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

You might also check the file permissions. This is either a problem of file location or file permission, as far as I know, so just make sure both are correct.

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

A pattern is a repeated decorative design, within the context of this discussion.

Ah, well, yeah, I guess that's the common man's definition. I guess I've been hanging out with the wrong crowd for too long. In my mind, the word "pattern" immediately invokes the more scientific terminology, as in "pattern recognition", "speech patterns", or "patterns of behaviour". So, to me, it's this definition I think of: "a combination of qualities, acts, tendencies, etc., forming a consistent or characteristic arrangement."

My point was that as long as there is a degree of freedom in choosing the specifics of this "characteristic arrangement", then there can be some randomness to it. For example, in pattern recognition, a classic example is a "table", as in, what set of qualities or features makes us recognize something as being a "table", that's the pattern, and being able to tell a table apart from a chair is the recognition part. If there were no random and unpredictable variations in the designs of tables, then it wouldn't be a problem of pattern recognition. See what I mean.

What makes a pattern a pattern is just as much its set of rules as its degree of freedom (or creative liberty, if you like). Without that degree of randomness, a pattern is not a pattern, it's just a thing (i.e., one particular definite object). If a Texan talks to me, I could say that I recognize the accent (i.e., speech "patterns") and deduce that he is from …

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

Or, maybe even better ...

Well, if we go into STL territory, we should do it in proper STL style ;)

template <typename OutputIter>
OutputIter fillFromFile(const std::string& FNAME, OutputIter it)
{
  typedef typename std::iterator_traits<OutputIter>::value_type Value;
  typedef std::istream_iterator<Value> InIter;
  std::ifstream fin( FNAME.c_str() )
  return std::copy(InIter(fin), InIter(), it);
}

and call it with:

std::vector<int> v;
fillFromFile("data.txt", std::back_inserter(v));
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Judging by your other post here, it seems that you busted three expensive phones in a row. In my experience, people who really have "bad luck" with their electronic devices are in reality just too careless with them. You might want to consider that. BTW, who's covering the bills for all these phones? I can't imagine he's very happy with you.

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

as if i was playing a heavy duty game for sevral hours straight

Did you by any chance happen to have discharged the battery completely while playing a heavy duty game? If so, I would bet your battery is toast. Reaching the minimum charge on a battery while drawing a lot of current from it can easily cause permanent damage to it, after which it can't be charged fully again.

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

A pattern implies order and random implies a total lack of.

Well, a pattern implies some order, not complete order. If you take a picture of a grass field, there is a pattern there, e.g., green color palette, vertical lines, a particular spatial frequency (number of grass blades per square meters), and so on, but the picture is definitely random.

Unless the rules of the pattern define exactly and completely how things should be, then any particular instance of a pattern is only that, one particular instance of it, i.e., a "sample". And a sample that is drawn from a random distribution is called a "random sample". With a simple substitution, we get "random pattern".

Further mind-blowing. Here's a random number: 5. How can you tell that this is a random number? If you want to know that it's indeed random, you need to know how I generated it, but if you know how the number was generated, can you still call it random?

you don't care which so you pick a pattern at random

In that case, I think the appropriate term is "arbitrary pattern". Arbitrary is the proper term for "I don't care which".

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

You have two equations:

C * 10^2 = 1
C * N^2  = 25

You can solve that for your two unknowns C and N. If you cannot figure out how to solve that, go back to high-school.

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

You're right, that makes no sense when you think about it. You should either say that "it's random", or say that "it has no discernible pattern". It's only when I was trying to edit down a paper (to a conference with a page limit) that I realized how a lot of expressions are redundant or self-contradictory.

But then again, a pattern can be random, but something random cannot have a pattern. Mind. Blown.

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

OK, so I have tried to use the latest option (the cnst_string option above, similar to the Sprout library). Still got a system-wide crash due to an out-of-memory condition when compiling. However, judging by what did compile, the compilation seems to take roughly half the amount of memory as it does with the "tuple-array" solution (literal_str_array), and also significantly less time. Nevertheless, it is still at least twice as much as the plain version with run-time strings (std::string) concatenation. And, it overwhelms my system again.

The resulting binaries are, all in all, 2.3% smaller with this scheme. but before this attempt, I got roughly a 10% reduction before just by optimizing my use of std::string in the plain version, and that before that, I got over 50% reduction by simply hiding the things that did not absolutely need to be exposed (i.e. through un-named namespaces, as I showed in the last post) and by removing the use of virtual functions in the core RTTI class (something I might show in an upcoming tutorial, i.e., how to implement a polymorphic class with no virtual functions of any kind). So, this 2.3% reduction, at the cost of significant headaches with compilation times and memory consumption, is, to me, not a good tradeoff.

Conclusion

Compile-time string concatenation, under the current language limitations (C++11 and C++14), does not scale well due to the overwhelming template instantiation depths (O(N^2) or type-traits invocations) that it entails. I'm quite sad about that, because I had pretty high …

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

Like Hiroshe, I had never heard of a CPU being clocked above 5 or 6GHz, and even then, that requires liquid cooling, or even liquid nitrogen cooling. It would seem that the world record is 8.8GHz.

Basically, the main reason why the CPU speed as been limited in the past 10 years is the physical limitations of heat transfer. A silicon chip and the heat sink on top of it has a certain maximum amount of heat transfer rate, i.e., there is a limit to the amount of heat that could possibly flow out of it, even under ideal conditions (ambient temperature at 0 Kelvin). And transistor technology has also reached its limit, pretty much. The energy consumption of a CPU, and thus, the heat coming out of it, is proportional to the number of transistor switches per second, i.e., the clock frequency. The higher the frequency the more heat is generated, and there is no way to reduce that amount of heat with existing transistor technology (or any transistor technology, i.e., there would need to be a major technology switch to something else (not transistors)). And the only way to increase the amount of heat that can flow out of a CPU is by lowering the ambient temperature or having a better coolant than air (such as water, and thus, the liquid cooling), but even then, you are still limited to the theoretical ideal limit, and I would assume that even that limit isn't much better than …

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

UPDATE

So, I found a major problem with the implementation that I posted originally. The problem is that the concatenation operator assumes that the second literal string list is not an actual list but only a single node. Therefore, the concatenation only really works for adding one simple string literal at a time. To solve this issue is actually non-trivial because of the linkage requirements on the literals (every string literal or string list must have external linkage, which is difficult to generate for intermediary values). One possible solution is to involve construct a compile-time tree of strings, instead of a list, which is also non-trivial. Another solution, which I present below, is to build a compile-time array of string literals instead. I have made a number of trials in that vein, and I thought it was interesting to explain some of the issues that occurred.

First, on the linkage issue. This is really an immensely annoying issue. String literals, as well as contant-expressions, do not have external linkage by default. In simple words, constants don't get "exported". Therefore, building a linked-list of string literals requires that every intermediate value (node in the linked-list) be given external linkage via a syntax similar to the one I used above in the number-to-string conversion:

template <>
struct ct_itoa<0> {
  static constexpr literal_str_list text =
    literal_str_list("");
};
// Define static member outside the template:
constexpr literal_str_list ct_itoa<0>::text;

where the definition outside the class template is what gives the constexpr text external …

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

Forget about my answer. Vijayan121's answer is definitely the right one, it makes a lot more sense than mine. I didn't know there was such as rule about pointer arithmetic in the standard, and I can barely believe that compilers manage to diagnose it! I guess the C++ compiler doesn't, though. Do you think there is any specific reason for that vijayan121?

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

What does the warning integer overflow in expression mean?

It means that the operation goes outside of the valid range of the particular type of integer. For example, if you have an integer of type unsigned char, then the range is 0..255 which means that doing 2 - 4 is an "overflow" because it goes negative, and, of course, 253 + 5 is also an "overflow" because it goes beyond the max of 255.

Why am I getting it?

For one, the &type - 1 operation could overflow by making the pointer "negative". Pointers are, in general, just unsigned integers that are interpreted as address values, and therefore, producing a negative pointer is an overflow error.

Another issue is that if you are in a 64bit platform, then pointers are 8 bytes long, while integers (int) are typically 4 bytes long. I think that by default, in C, the operations are done in the default integer type int unless it is explicitely made otherwise. But I could be mistaken, I'm not super well versed in the soft typing rules of C. But when I generate the assembly listing for your program (after a few tricks to prevent optimizations), this is confirmed by the following assembly code:

leaq -8(%rbp), %rcx    // &x -> rcx (64bit reg.)
movq %rcx, %rsi        // rcx -> rsi (save it)
addq $-4, %rcx         // substracts 4 from &x
subq %rcx, %rsi        // does (&x - (&x - 1))
movl %esi, %r8d …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

could you please modify my code according to that requirement ?

You just do this:

delete[] p1;

Any memory allocated with new something[n]; must be deleted with delete[].

As for being able to access the memory after you deleted it, well, that's like rubberman explained. When freeing memory, the memory is still there, and it's not cleared or overwritten, it is simple marked as "free" to be reused in a future allocation. It is undefined behavior to try and access it again (although it usually works, it could crash or give you garbage).

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

When I dynamically allocate mem within a function, do I have to still manually release it?

Yes. Everything that is allocated must be deallocated. If you allocate memory inside a function and don't release it before exiting the function, then that memory will be leaked (or in more precise terms, it will be "unreachable" memory, because it is memory that has not been freed, and has no more pointers anywhere pointing to it, and thus, "unreachable").

Or does it go away once the function has run and returned (like local variables)?

No. Local variables "go away" because they are part of the function's stack frame (static memory allocated for the duration of the function's execution). Dynamic memory is allocated on the "heap", which is not automatic, i.e., you have to manually allocate and then manually deallocate everything.

If I do have to release it, since it's basically a pointer can I do that from main?

Yes, you can do that from anywhere you want, but you do need to have the pointer value accessible.

Do I have to return the address to release it from outside the function?

Exactly. If you want to be able to release the memory from outside of the function, then you need to return the pointer that needs to be deleted. Basically, the place where you decide to release the memory from needs to know the address of the memory you want to release, otherwise it can't …

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

I would say C++ and Python. I guess Java could be an option, and I remember seeing some half-serious Java code in robotics. As for C# in robotics, that must be a joke, right?

By far, the most widespread languages for robotics are C, C++ and Python, depending on what "level" you are at (drivers, embedded systems, micro-PCs, controllers, high-level scripts or state machines, etc.). The brunt of it is in C++. It's basically C for dealing with hardware, C++ for everything that is important, that matters and/or is complicated, and Python for plugging the main pieces together or for helper tools (visualization, GUIs, scripts, etc.).

Besides that, there are, of course, hardware-specific languages such as KRL/RSI (for Kuka robotics). And there is also a number of other specialized tools that are use in robotics and automation. In more academic settings, people sometimes used Matlab/Simulink, although I find it very limiting (and very quirky to work with).

Of course, if you move one step removed from actual robotic hardware, you can pretty much use whatever you want, and Java certainly occupies a big space there. I'm talking about "ground station" work here, i.e., the stuff you run outside the robot, in a ground station computer, like planning or mapping algorithms (e.g., SLAM). But I still would not recommend using Java anywhere.

In my personal experience, probably 95% of robots I have seen or worked with run on C/C++ code, and the rest run on Matlab/Simulink (Real-time Workshop) code. The only …

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

You can use the tellg and seekg functions to re-establish the cursor (get pointer). As so:

std::streampos p = filestream.tellg();
stringstrm << filestream.rdbuf(); 
filestream.seekg(p);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Remember, this is a c++ forum so your answers are going to be somewhat biased.

But there is also a reason why the C++ forum is the first one on the list, and the most active. ;)

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

The preOrderHelper function should take a TreeNode pointer, not a Tree pointer. It's probably a simple typo (by you or the author). It should be:

void preOrderHelper( TreeNode<NODETYPE> *ptr) const

Just like it is for the other helper functions.

If you read the errors, they give you a pretty clear indication of the error. The error messages are saying that you are trying to call the helper function with a pointer to a TreeNode pointer, but the helper function takes a Tree pointer. When that's the error, there are really only two possible solutions, either you should be calling the function with a Tree pointer instead, or the function should be taking in a TreeNode pointer instead. In this case, the latter is the solution.

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

Yes, I was aware of that implementation. It's very impressive, but at the same time, I feel that it has too much stuff in it, and that it is too heavy-duty.

In that library, concatenation is implemented by turning the string literal into a variadic template argument pack of chars and then unpacking it as a sequence of chars that brace-initialize an array of chars of the same size. It does have the advantage that is generates an actual char array (as opposed to linked-list of literals), which makes other operations like substring and iterators a lot easier (not to mention that it relieves some of the linking constraints on the objects being concatenated, which is very nice), but it is also a very heavy compile-time mechanism to put in play.

Doing fancy stuff like that with variadic templates has not been a joyful experience for me. I've found that the amount of code-bloat and compilation times that it causes is overwhelming. It's also very hard to control the proliferation of template instantiations with variadic templates.

My aim with this string concatenation stuff was mostly to avoid going into template meta-programming techniques too much (except that it is needed, afaik, for number-to-string conversion). For instance, there are plenty of ways to concatenate strings (and do other things) once you move onto things like boost::mpl::sequence and similar approaches like in sprout. Sprout is certainly not as bad as using Boost.MPL for this purpose, but it is still pretty heavy. And also, …

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

As an added little bonus, you can also use this literal string list class to perform some compile-time integer to string conversions:

static const char str_digits[] = "0123456789";

template <unsigned int N>
struct ct_itoa;

template <>
struct ct_itoa<0> {
  static constexpr literal_str_list text =
    literal_str_list("");
};

// Define static member outside the template:
constexpr literal_str_list ct_itoa<0>::text;

template <unsigned int N>
struct ct_itoa {
  static constexpr literal_str_list this_digit =
    literal_str_list(str_digits + (N % 10), 1);
  static constexpr literal_str_list text = 
    ct_itoa< N / 10 >::text + this_digit;
};

// Define static members outside the template:
template <unsigned int N>
constexpr literal_str_list ct_itoa<N>::this_digit;
template <unsigned int N>
constexpr literal_str_list ct_itoa<N>::text;

The method is simple. It's a classic template meta-programming recursion to compute a static constexpr string list object that contains the result.

The only tricky part here, and it's an important one, is that the static constexpr members of the class templates (ct_itoa) must be defined outside the classes (and that is true, even for non-templates). This is due to another tricky rule about C++ linkage. Static const/constexpr data members that are defined inside a class declaration have no linkage, i.e., they disappear after compilation. This means that our list of string literals will be broken as they refer to non-existent constexpr objects. Because of this, compilation will succeed, but linking will fail!

If that makes you feel completely lost, don't worry, we are very deep inside the rabbit hole right now.

All you really need to know is that …

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

No, it's not a waste of time. It's one of the most powerful and fundamental programming languages out there. Even if you don't end up programming in C++ in your particular job or field, it is not a waste of time to learn it.

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

I agree with Hiroshe about UML diagrams. I have rarely found them to be useful. I think that they are simply too detailed. If you have to make a diagram that has all your classes, with all of their data members and methods (functions), you are basically doubling your workload (because it takes about as much time making that diagram as it takes to write the code), and you don't really get that "big picture" benefit because there are so many details in a UML diagram that anything that is non-trivial will end up as a huge UML mess of details and connections. I see UML diagrams more as a way to graphically document an existing design, not as a tool for designing it. But I sometimes draw higher level diagrams, with none of those unecessary details, only to map out the building-blocks of the software and their inter-dependencies (very important!).

I also don't see UML diagrams being used that much as a form of communication about software design ideas either. All seasoned programmers know code very well, and therefore, it seems like a much more natural language of communication than UML diagrams. What I tend to see the most is people expressing their design ideas in the form of snippets of code (often just stubs) that illustrate how it should work ("use-cases") or how it could be done (e.g., like the skeleton of an implementation, maybe some pseudo-code in there). And I think that this seems to be a …

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

I got a Nexus 5 a few months ago. I love it, it works great and it's fast and crisp and all that.. no complaints. Also, the wireless charger is really nice to have.

I guess the SG S5 has higher specs but like Agilemind said, that's pretty much plateau'd at this point. And I don't know how it is where you live, but here, you can buy two Nexus 5's for the price of one unlocked SG S5. I just can't see how the slightly higher specs can justify that.

PS simLocking is just another way for operators to 'subsidize' phone prices by having their profit come from the monthly plans

Also, don't forget those "deals" where if you enter a new contract you can get the phone almost free.. but of course, later on, when you want a new phone you can't get out of the contract and you now have to pay full price (or more) for the new phone.

I hate sim-locking. My first phone was sim-locked. Then I realized what that meant. I never bought a sim-locked phone again, and I support Google's move to undermine that whole scheme by putting out reasonably priced unlocked phones.

Part of the reason phones are so expensive to buy unlocked is because they want to steer people into these locked-in contracts instead, so they can squeeze more out of you. Basically, companies would look bad if they simply said that they don't sell unlocked phones, it …

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

Does this mean that ListNode can access Lists's private members

No, it's the other way around. By declaring List as a friend, the ListNode class gives access to its private members to the List class. It's like an invitation, ListNode invites List into its access-space.

Just think about it as a house. ListNode has a house with private things in it. It declares List as its friend, like giving List the keys to its house and thus access to its private things.

If it were to work the other way (as in, "ListNode can access List's private members"), then it would be the equivalent of ListNode declaring itself the friend of List and inviting itself into List's house. You can't do that, just like you cannot walk up to some stranger's front door and declare yourself their friend and invite yourself in. It always works the other way, they invite you in.

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

Hi all,

I was just playing around with some ideas about optimizing a core piece of my library: the run-time type identification system (RTTI). What does that have to do with compile-time string concatenation? Well, the whole point of the RTTI is to provide information on the type of objects, and a string representation of that name is a pretty central part of that (as well as a hash value). Type names are made of identifiers, which are names that are known at compile-time, and could thus be compile-time string literals (that means things like "Hello world!"). The problem is, for complex types, like templates, many compile-time strings need to be assembled or concatenated to form the complete type names. At that point, I had to switch over to run-time code (e.g., using std::string or C-style functions) to form those compound strings. Why? Because there is no way to concatenate strings at compile-time, or so I thought...

What makes this difficult is that normally, when you concatenate strings, you just create a new chunk of memory big enough for the two original strings and then copy the two strings one after the other. Easy right? Well, there are two problems. First, you cannot "create a chunk of memory" at compile-time because there is no concept of memory at this point. Second, you cannot copy data because that would imply changing things, and you cannot change compile-time constants. So, clearly, the traditional method won't work.

Welcome to the world of pure …

ddanbe commented: ++ ! +15
Hiroshe commented: Excellent! +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I'd finally be able to use ctrl-c and ctrl-v

But I would expect that ctrl-C would be sending a kill signal to the command currently running. Most command-line interfaces that I know of use ctrl-C for kill and ctrl-Z for hard kill of the programs. It would be weird if they changed that. Usually, the copy-paste can be done with ctrl-shift-C/V.

Here it is ;)

That's just the GNU coreutils library. This is a tiny part of the base MinGW MSYS environment. And the coreutils package is lacking some pretty critical tools, like bash, grep, find, awk/gawk, tar, gzip, etc... You should just go with MSYS instead to have a more complete environment. And as far as I know, when using coreutils in a cmd.exe session, you don't get the Bash features like redirections and pipes. Not having pipes makes the whole thing kind of pointless, no? At least, with MSYS, you get Bash, and thus, pipes, redirections, and the whole bash language for bash scripts... now we are starting to have something respectable as a command-line environment.

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

The .find() function (in string class) is perfectly fine. I've never heard anybody say that there was anything wrong with it. It's a simple function to find a matching character or string within a string, what could go wrong with that?

In general, the only standard functions that one could say are deprecated or not recommended will be found within the legacy C libraries (any header starting with "c", like <cstdlib> or <cstring>) because some of them are not safe or have bad style.

Since C++11, one might argue that if you are doing a lot of string manipulations, such as finding particular tokens in a string, or some other general form of parsing, then it would be preferrable to use the <regex> (docs) library instead. However, regex is not widely available yet on compilers, and it's not the easiest library to work with. You only need for more serious parsing (an intermdiate between using simple string functions, and using a real parser generator library like Yacc, Bison or Boost.Spirit.

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

Installed this package

Would you mind tell us what the name of that 'package' is?

BTW, in Windows, you shouldn't really be using cmd, because it sucks and it's deprecated, use PowerShell instead, which supports most of the bash commands too.

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

Are you talking about Cygwin? The Unix emulator for windows, which has, like Linux, all the unix commands plus most of the GNU programs (and others) that can be installed via its package manager. Cygwin is one of the first program I install on any Windows machine that I'm gonna be using.

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

C++ uses pointers and have memory leaks , where java doesn't have pointers

I've been writing C++ code for years, and I don't remember the last time I had a real memory leak problem. The idea that C++ code has memory leak is a complete myth. Beginners might have such problems for maybe a few months at the beginning, until they understand the basic tricks (RAII, smart-pointers, value objects, etc.), that's been my experience, at least. In the C++ community, people generally characterize memory management in C++ as "automatic scope-based resource management", emphasis on the "automatic", because in decently written C++ code, resources manage themselves.

Also, Java does have pointers, they are simply hidden from the programmer. In fact, by any measure, Java has exponentially more pointers than C++ has. Java is a reference-semantics language, which means that every object you see in the code is, in reality, a hidden pointer to where the real object is (i.e., "reference-semantics" means that all variables must be understood as being pointers / references to something). This means that there is an extra layer of indirection on top of everything, everywhere. C++ is a value-semantics language, which means that every object you see is the object itself, i.e., variables must be understood directly as variables. The only indirections there are are the ones that you create, by using pointers or references explicitly. This crucial difference between the languages is, IMHO, the most important one, by far.

Reference-semantics in Java is what …

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

is adding m_y, m_m, m_d, considered as cheating?

Nothing is considered "cheating", but there are trade-offs. Keeping the year / month / day values within the class will add to the memory used by the objects (instead of just one number for the days since some fixed date in the past (called "epoch")), but you can, technically, respond faster to requests (calls) for the year / month / day (or some derivation of that). However, you also have to understand that this will not allow you to get away with not having to write code for converting between the "day-since-epoch" value and the "year-month-day" values. Whichever way you do it, you still need to provide conversions back and forth. If you store only YMD, then you need to convert when getting or setting the date as day-since-epoch. And vice versa if you only store the day-since-epoch. And if you store both, then you have to guarantee that they are always referring to the same date, meaning that you will have to do conversions all the time, e.g., if you set the day since epoch, then you have to update YMD data to match it, and the same goes for every other function.

So, you will have to write the conversion code. As far as how to do it, well, you have to handle the leap-years and the various number of days in each month, but it's a fairly straight-forward thing to do. If you have problem writing that …

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

Why couldn't I do this instead (having that same line there with the <el> being removed)?:

Because the compiler will interpret this declaration as a regular function that takes a particular Array<el>, not as a particular specialization of the function template that can take any Array<el>. As I said earlier, this is one of those mind-bending things, but you'll understand it eventually.

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

To create the input output operators as friends of your Array class template for a specific "el" type, you need to do the following set of little tricks:

// Make a forward-declaration of Array:
template <typename el>
class Array;

// Declare the operators:
template <typename el>
std::ostream &operator<<(std::ostream&, const Array<el>&);
template <typename el>
std::istream &operator>>(std::istream&, Array<el>&);


template <typename el>
class Array
{
    // Declare the specializations as friends:

    friend std::ostream &operator<< <el>(std::ostream&, const Array<el>&);
    friend std::istream &operator>> <el>(std::istream&, Array<el>&);


    // ... rest of code for Array...

}

// And then, put the definitions of the operators:

//overloaded input iterator for class Array
//inputs values for entire array
template<typename el>
istream &operator>>(istream& input, Array<el>& a)
{
  //output private ptr-based array
  for (size_t i=0; i < a.size; i++)
    input >> a.ptr[i];
  return input;   //enable cin >> x >> y
}

//overloaded output operator for class Array
template<typename el>
ostream &operator<<(ostream &output, const Array<el>& a)
{
  //output private ptr-based array
  for (size_t i=0; i < a.size; i++)
  {
    output << setw(12) << a.ptr[i];
    if ((i+1)%4 == 0)   //four numbers per row of output
      output << endl;
  }
  if (a.size%4 != 0) //end last line of output
    output << endl;
  return output;
}

And just a final note on your terminology:

I commented out the definition and the implementation

In C/C++ terminology, the words "definition" and "implementation" are essentially synonyms. The word "definition" is just the way that the standard documents refer to "where the actual code is", i.e., the …

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

I tried the actual code, and there are some "real" errors like in the != operator, where you have !(this == right) instead of !(*this == right), because this is a pointer, so it needs to be dereferenced to get a reference that can be compared with right.

In the assignment operator, you have if(right != this) which should be if(&right != this) to compare the address of both objects, to prevent self-assignment. Also, that function is missing the return statement return *this;.

There is a difference in the signature of the input operator >>, because the friend declaration has the array reference as non-const (as it should be in this case), and the definition of that operator has a const-reference.

The other obvious problem is the undefined behavior that NathanOliver pointed out, which you should so as this:

ptr[i] = el();    //default-construted value

which means that any class object will just be default initialized, while primitive values (like int, double, etc.) will be zero-initialized.

Another interesting little problem is with your friend declaration for the << or >> operators. This is a bit of a crazy mind bender, but essentially, when you declare a friend function like this, within a class template, you end up declaring, as a friend, a regular function (non-template) as a friend to a class template, but that regular function will only get created when you use the class template for a particular template argument(s). Long story short, there is no way the …

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

MACROs are a kind of find-and-replace feature with some additional useful benefits. First, they can take parameters which will be replaced inside the MACRO's body. But be warned, they should not be used as substitute for functions, i.e., if you can do it with a function, use a function because MACROs can be dangerous in the sense that they can introduce weird bugs. Function-like MACROs can be useful for generating code that could not be generated otherwise (via templates or functions). Additionally, MACROs can be used in simple pre-processor logic statements (#if, #ifdef, etc..) which can allow you to turn on and off certain sections of code depending on the value (or existence) of certain MACRO symbols.

Asserts are used for checking conditions that should never occur unless there is a bug in the code, i.e., they're sanity checks. The point is that there are a number of checks, such as range checks, that don't need to done when you have completely bug-free code. But until you know for sure that you don't have bugs, you need to do some debugging and quality assurance (unit-tests, etc..). During that debugging phase, it's useful to perform a number of checks everywhere to catch as many bugs as possible, but one you are done debugging, you don't want to have to go through the code and remove all those checks. So, asserts are checks that are only enabled when the code is compiled in "debug" mode, and get removed by the compiler when …