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

I think that this sounds better:

"Give someone a ticket for texting, and a life could be saved"

It doesn't quite have the same meaning, but it's actually more accurate (the life saved might not be the life of the texting-and-driving person, but of an innocent victim). I like these kinds of simple cause-effect sentences without all the fluff of using gerunds and sub-phrases. It's often clearer, shorter and punchier.

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

Well, option 2 is certainly not possible. The problem is not with the instantiation of the class but with the identity of the instantiation of the class (or specialization). You cannot insert, within the class, the entity that defines its identity, it's a circular logic problem, similar to trying to create an object of an incomplete type.

Option 1 could technically be done, but there are still a number of problems with this. For one, allowing the hidden creation of an externally visible symbol is not something that would sit well with some people (not me personally, but some people wouldn't be happy about that).

Another important issue would be about this situation:

demo<"hello"> a;

demo<"hello"> b;

Are a and b of the same type? No. That's a surprising behavior that most novices wouldn't expect, and also the compiler cannot, in general, be required to diagnose this kind of a problem (even though it could emit a warning). In other words, this could easily be a source for a silent bug. Now, the programmer could fix this by doing this:

typedef demo<"hello"> demo_hello;

demo_hello a;
demo_hello b;

but is that really better than this:

char hello[] = "hello";

demo<hello> a;
demo<hello> b;

And also, with the typedef solution, you still have a problem when the type demo_hello is used in different translation units, because, again, their types will be different. And that leads to a violation of ODR (One Definition Rule), which the C++ …

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

This problem is actually very straight forward. It is allowed to have pointers are template parameters. However, you can only instantiate the template with a pointer to something that has external linkage. So, your example works (with text) only works because text is a global variable with external storage. If you change its linkage to internal, it doesn't work:

template <char * P> struct demo { };

static char text[]="hello";

// since this is already allowed:
demo<text> dt;   // error, text has internal linkage

The problem with this is that things (variables, functions, etc.) that have external linkage have a program-wide address, i.e., an address that is resolvable during compilation because it will end up at some fixed address in the data section of the final program. This allows the compiler to form a consistent instantiation of the template.

When things have internal linkage or no linkage, there is no fixed address, in fact, there might not be an address at all (could be optimized away, or created on the stack). Therefore, there is no way to instantiate a template based on that non-existent address. When you have a literal string, like just "hello", it's a temporary literal with no linkage. This is why this thing cannot work, and will never work.

You have to understand that C++ is really close to the metal, and most of the limitations that may seem excessive are actually there because this is where the real world implementation issues collide with theoretically …

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

That's interesting. Another show that uses this pattern very well is Castle, where the overarching plot is finding out who murdered Beckett's mother, and why. But it works well, I think, because it's not so central to the show and the show is enjoyable on an episode-per-episode basis. They use that mystery mostly in the season finales where one or two of the last episodes involve a new piece of the puzzle. I think that they do this well because if you follow the show religiously, it creates additional interest in the finales and the show as a whole, but it's not so much that it's overbearing (too much mystery, like in X-files) or an essential part of being able to enjoy any random episode that you happen to catch.

As with a lot of other things, it's all about balance. At some point, the producers / writers have to decide whether the show is a series to be followed religiously (e.g., Game of Thrones) or an episodic series (e.g., Castle, Star Trek series, Star Gate series, etc.). And if it's the former, you have to have a clear idea of when (and how) it's going to end, otherwise the plot is bound to suffer (like Lost). Lost probably should have run only for about 1 or 2 seasons, but it was so popular that it was too tempting to extend it, and it ended up going all over the place, and was becoming very frustrating. But I don't think …

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

the very very safe side, in section 25.2.2 the use of string litteral as template argument (apparently correctly declared erroneous on page 724) but used later happily in 2 examples on page 725
Vec<string,""> c2
and later
Vec<string,"fortytwo"> c2;
that surely must have been written by the same student who wrote the ADL example, right?

Wow... you are pointing out some real flaws in that book. I'm starting to have doubts about the care that Stroustrup put into that book (which I have not read, beyond what you have pointed out so far), because these are some serious things that I'm pretty sure any competent reviewer should have picked up on. In that example, it is not quite using a string literal as a template argument, but it's still wrong, in fact, it's double wrong. The idea here is that the string literal is (presumably) converted to a constexpr std::string object and that that object is used as the template argument. That's wrong because (1) you cannot use arbitrary literal types as template value parameters (only integral types), and (2) a constexpr string is not even a literal type because it is a non-trivial class. There was a proposal for C++14 for allowing arbitrary literal types as template value parameters, but even though Stroustrup states in that section of the book that this restriction is there "for no fundamental reason", I think that this proposal is dead in the water, AFAIK, because there are indeed fundamental …

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

Definitely, you need to go for Boost.Asio. It might seem a bit weird to use at first, but just follow the examples / tutorials, and you'll get the hang of it.

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

1) Section 28.2.1.1 p784

You are indeed missing the main point here. The reason why you want to avoid the template instantiation is because of the failure case, not the successful case (as you tested). The thing is, if you want to instantiate a template like Condition<A,B,C>, the types A, B, and C must be instantiated before you instantiate the Conditional template. By analogy to normal functions (instead of meta-functions, what Stroustrup calls "type functions"), before calling a normal function, each parameter must be evaluated. Similarly, before instantiating Conditional, all arguments (A,B,C) must be instantiated.

The case that Stroustrup is describing here is when one of the arguments (say, B) cannot be evaluated when the condition (A) is false. This isn't really a matter of template aliases versus the "old-style" typename ..::type technique. For example, if you had the following:

typename std::conditional<
  std::is_integral<T>::value,
  typename std::make_unsigned<T>::type,
  T
>::type

There is a problem because when the typename std::make_unsigned<T>::type argument cannot be instantiated (because the T has not unsigned variant), then the whole thing cannot be instantiated. In reality, in all the cases when make-unsigned would fail, we also know that is-integral would instantiate to false, and therefore, the make-unsigned argument is never really needed in that case. In other words, the make-unsigned argument is prematurely instantiated, and this can cause obvious problems. In the example here, when is-integral fails, the conditional is supposed to return T, but instead, it will fail with a compile-time error.

This is also …

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

Just so that people understand what this discussion is about. I'm gonna post the essential bits of code that from that section of the book.

The first solution that he puts forth (that you are critiquing) is this:

template <typename Node>
struct node_base {
  Node* left;
  Node* right;

  node_base() : left(nullptr), right(nullptr) { };

  void add_left(Node* ptr) {
    if( !left )
      left = ptr;
    else
      // .. do something else (?)
  };

  //... other tree-manip functions..

};

template <typename ValueType>
struct node : node_base< node<ValueType> > {
  ValueType value;

  node(ValueType aVal) : value(std::move(aVal)) { };

  //... other value-access functions..
};

Now, at face-value, this seems, as you said, sort of pointless, but I would disagree, and even more so considering that this is a bit of a set-up for what comes later in the same section (the next couple of pages), where the motivation for this becomes even more.

But you can already see a hint of what the purpose of this "very complicated structure" is. And by the way, if you think this is a complicated structure... man, wait until you get a load of some serious data structure implementations, this thing is a piece of cake in comparison. So, the thing to observe here is that in the base class I wrote "other tree-manip functions" and in the top-level class I wrote "other value-access functions", and that's already one reason (and not so obscure either) for splitting things up like that, because, if nothing else, it …

StuXYZ commented: Very clear +9
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

lot of people usually don't use const with pointers even when they don't intend to change what the pointer points to, and I just want to know why that is.

This is mainly a reflection of the ineptitude or laziness of many programmers in C++. First of all, const-correctness is something that is very unique to C++ (and D), and doesn't really exist in its complete form in any other language (it exists in C (since C90) but it's limited, and there are some minor features in Java and C# that attempt to mimic it but they are far too limited to be used in the same way). Even in C, using const is not too popular for historical reasons (lots of C programmers and code dates back to before 1990). In other words, anyone that is coming to C++ from almost any other language is probably not familiar with or used to writing const-correct code.

Another reason is that some people lack the technical know-how to write const-correct code. I mean that once in a while, you have to bend the rules a little bit, either because you are interfacing with an older library, or because you need to modify some data member within a const member function. C++ gives you some tools to bend the const-ness rules, in particular, the const_cast and the mutable keyword (to apply to data member that are "exempt" from the constness of their containing objects). If you don't know how to …

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

I agree with deceptikon. Learning the way you describe is nice from the perspective of acquiring a deep understanding of everything. I did something similar with mathematics, from basic logic axioms up to calculus of variations, and it was very enlightning and amazing. However, doing this requires, as a pre-requisite, a strong and unwaivering interest in the subject matter. I already did a lot of math and loved it before I went on this bottom-up journey. You have to build the passion and the curiosity before you go on that road.

Remember, the challenge of teaching is not about what is the most logical way to present the material, it's about sustaining interest or fostering a passion for the subject. If you had a matrix-style brain-plug, I agree that your description would the correct order in which to download the knowledge (bottom-up), but until then, we are stuck with those real challenges of pedagogy.

Personally, I sort of learned from the top to the bottom. I started with a language heavily inspired from Visual Basic (a kind of open-source clone of VB). I was instantly hooked on this amazing power to create applications that looked just like the "professional" software, I was just amazed that I could do that with just a bit of brain-to-finger gymnastics. I got tired of the limitations of this VB-like language (and library), so I moved on to something more "mid-level", which was Delphi (an object-oriented language somewhere in between C++ and C#, but derived …

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

This actually has nothing to do with the move constructor.

The reason why the move constructor is not called is because of return-value-optimization (RVO). This is one of the rare cases where the compiler is allowed to change the behavior for optimization purposes. The point here is that RVO allows the compiler (under some circumstances) to construct the return value of a function directly within the memory of the variable in which the result is to be stored in the call-site. So, the return value of the function createA() (called "a" internally) will be created directly in the same memory that the parameter "a" to the function print() will occupy. This allows the compiler to avoid an unnecessary copy (or move). This is not always possible, but it often is, and it certainly is happening in the trivial case in your example. So, that explains it.

Now, like I mentioned, there are cases where RVO cannot be applied. And so, we can use that knowledge to deliberately disable RVO by writing "stupid" code within the createA() function. Now, this could depend on how smart your compiler is and the level of optimizations enabled. Basically, the main requirement for RVO to be applied is that there should be a single return value in a function, this means, either you have a single named variable for the return value and all the return statements return that variable (this case is called "Named RVO" or NRVO), or you have a single return statement. …

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

I am guessing that you have some sort of memory leak or memory corruption. The out of memory error occurs either if you literally run out of memory (e.g., from a memory leak in a tight loop), or if you corrupted the heap completely (e.g., by freeing memory twice). From you valgrind tests, it would appear that you have a memory leak. In valgrind terminology, it reports "possibly lost" (or "definitely lost") for memory that has not been freed and no longer has any pointer to it, which is, by definition, a memory leak (you have memory that you cannot possibly deallocation since you no longer have a pointer to it).

Without showing us your code, there isn't much we can do to help. This is a case-by-case issue, so, there is no "solution". A memory leak generally comes from not calling "delete" on memory that you allocated with "new". Sometimes this is obvious (e.g., just forgot to put the delete), and sometimes it's less obvious (e.g., the delete is in a place that isn't reached by the execution under some or all circumstances). The general solution to solve that issue is to use RAII classes (or see wiki).

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

@Excizted: I have to warn you that your post is close to violating the "Keep it Pleasant" rule of this forum. We are a welcoming community and we strive for enriching discussions. Your post used bad language and insulting words. As for your remark on "and so what? Do you want us to care?", I must remind you that caring about people's problem is a pre-requisite for helping them, and therefore, stokie-rich is certainly justified in expecting us to care about his problem, because we do, otherwise we wouldn't come here to help people.

@stokie-rich: I can't help you with PHP/SQL questions because I don't know anything about that, I mainly posted here as a moderator. However, I would suggest you post what you have tried and describe the specific problems you are having with it. You have to help us help you, by being clear, specific and show your efforts to solve the problem.

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

I would assume that POCO_LONG_IS_64_BIT detects if the size of the type long or int. Usually, on 64bit platforms, the int type is still 4 bytes (32bit), it's only that pointers are 64bit (to allow more than 4Gb of RAM) and that there are 64bit registers available natively (which could accommodate 64bit integers without having to break them up).

So, the logic error here is that you assumed that a 64bit platform necessarily means 64bit integers. Most compilers will not generate 64bit integers (unless it's long long int). Also, a 64bit platform does not necessarily imply that the memory is aligned on 8 byte boundaries, in fact, I don't think that it ever is, and therefore, 4 bytes is really the ideal size for an integer that doesn't necessarily need to be that big, i.e., for int or long.

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

I got an automatic update of openssl yesterday, as part of the regular automatic updating of all software on Linux (Kubuntu). It contains the fix for that bug, as it's stated on the website. I would assume all other decent Linux distros' repository have been updated too in the past couple of days. If a vulnerability can be found and fixed within a couple of days, I feel pretty safe. I'm pretty sure these kinds of vulnerabilities are found all the time, it's only a matter of how quick they are patched, and to that Linus' law still holds: "given enough eyeballs, all bugs are shallow".

I think that Mojang's reaction was a bit rash. As far as I understand the reports, this bug was just stumbled upon by some developer, and quickly fixed as a consequence. There is no evidence anyone actually used it or was even aware of it before the developers who reported it found it.

As for people who are still vulnerable to this because they are still using an older version, well, that's their problem. Core security tools like openssl are the kind of things you should be updating as soon as updates are available, obviously.

if they're not worried about about it should we all be?

What do you mean? We don't have worry, now, about that exploit since it has already been fixed. Or are you implying that we should be worried about why the banks were not worried? …

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

These are numbers for the U.S., obviously. They seem somewhat high, but I think it's because they just have one average for each job title. I would expect that starting salaries are quite a bit lower than that. For example, for just basic "programmer", they quote around 75k$. Someone seeking a programmer's job right out of college (or tech. school) should probably expect something more along the lines of 45-65k$ to start with. So, that number of 75k$ is the average, and is seems reasonable for mid-career or so (e.g., after 10-15 years of working). And then, it goes up from there when you look into more sophisticated job titles (many of which are also exclusively for people with already many years of experience, so they are often much later in their careers).

So, considering that, and also considering that it can vary a lot depending on the field of application (e.g., programmers writing financial analytics software probably make upwards of 250k$, at least, that's how it would appear on job postings), I think the numbers there are within the right ball-park (seem like legitimate averages), but there is obviously a big margin to account for varying experience and application domain (and size of the enterprise).

These are also the ball-park numbers for most professional jobs (e.g., engineers, accountants, doctors, lawyers, etc.) in the western world.

It is 12 times of what is good salary here.

Yeah... that's a sad reality for you. It must be quite frustrating …

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

Do I need a header file and a .cpp file both to use a custom defined class?

In addition to AD's remarks, I just want to clarify what you mean by "use". To create a custom class, it is conventional to place the declarations in a header file and the definitions in a cpp file ("definition" means "implementation"). But as AD remarked, you can, in some cases, depart from that convention, notably for short functions (inline) and templates, in which cases, you put the definitions in the header file directly. To use a custom class in some other code, you need to include the header file in order to compile that code, and then, you need to link with the compiled cpp file for the custom class. The compiled cpp file can be either compiled along with your other cpp file(s), compiled separately into an object file (.o or .obj) and then linked with your other cpp file(s), or it can be bundled into a static or dynamic library and then linked with your other cpp file(s).

I highly suggest that you read my comprehensive tutorial on compiling C++ code.

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

what do you prefere for naming: database - c++ - java - php?

Like they say: "When in Rome, do as Romans do."
To me, it's all about whatever is conventionally used in the project or language in question. None is intrinsically better than another, the only thing that makes one notation superior to another is how accustomed the most-likely readers are to it, that's why they're called "conventions". If I program in my C++ library or in Boost, I follow the STL-style custom (lower-case, underscore-separation for most things, except template arguments (and concepts) in CamelCase), because that is the established custom there (and in most "expert" C++ libraries). If I code in Clang (also C++), which makes abusive use of OOP and is heavily influenced by Java and Objective-C, then I write in that Java-style CamelCaseObject.doSomething(); style.

I tend to prefer the C++ STL style because that's what I'm most used to, that's all. I tend to dislike the Java-style CamelCase notation, but that is mostly because I do a lot of C++, and Java-style notation is usually an indicator of Java-style programming, which, in C++, is a guarantee of very poor code quality. So, that's why it's off-putting to me, because I get a bad feeling about what I'm getting into.

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

Why dont try to sort your vector in ascending mode ?
After that the first element is the smallest, the second is the next smallest.

Because sorting an entire array just to obtain the N smallest elements is very wasteful. And especially in the context that the OP seems to be referring to (file-system indexing), that vector is probably very dynamic, and probably much bigger than the number of N smallest elements required. Keeping this vector sorted at all times would be very bad.

One solution, as presented by vijayan121, is to use the nth_element algorithm which partitions the vector such that the value that would appear at the Nth position in a sorted vector will appear at the Nth position in the partition and all the lesser elements will come before it, and all the greater elements after it. Because this does not sort the entire vector, i.e. the two sub-sequences on either side of the Nth element are not sorted, this operation can be done in linear-time O(S) (if S is total size), which is much better than sorting, which is O(S log(S)). If you want the N smallest elements to be sorted, you can sort that sub-sequence after you call nth_element.

The reason that vijayan121's code does not compile for you is probably because it uses C++11 features, which your compiler may or may not support, and are not turned on by default (you need the -std=c++11 option). Here is a C++98 version:


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

A character array is just what it sounds like, it's a raw array (sequence of contiguous memory) of characters (1 byte numbers that are interpreted as characters when printed on a screen) with the end marked with a 0 character (null-terminated strings). That's about all you get with a character array, it's just raw memory and you have to manually allocate / deallocate it, use C-style functions like strcmp or strcat to do operations on that memory, and you have to worry about capacity. Character arrays are essentially the only option in C for representing strings. It can be useful to know about them and how to work with them, mainly as a way to build your "low-level understanding" of things, but they are not really used in practice in C++, unless you are dealing with some C code.

Strings, as in, using the std::string class, are the proper way to deal with strings in C++. This is a class that encapsulates a dynamic array of characters and provides a number of useful features to manipulate strings. For one, it automatically handles the allocation / deallocation of the memory, as well as increasing the capacity whenever needed (as you append stuff to the string). That, by itself, is a sufficient reason to use C++ strings over the C-style character arrays, almost always. In addition, C++ strings have a number of nice functions and operators that allow you to compare, concatenate, split, and transform the strings very easily and safely. They …

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

Software engineering as it currently exists has little to do with the rigor of modern physical engineering, however; even achitecture, the 'softest' of the engineering fields, is far and away more rigorous.

Amen to that!

The field needs, absolutely needs, some kind of professional standards if it is to hold professional standing.

I totally agree. I was fairly recently at a conference about guidance systems (i.e., software for drones, airplanes, rockets and spacecrafts), and 3 out of 4 keynote speakers talked exclusively about the very serious need for strict methodologies to guarantee safety and correctness of software. This is actually an insanely difficult problem, and the advances in this department are ridiculously insufficient right now.

This would be a trade course rather than a university curriculum, and end with an multi-year apprenticeship and a professional certifcation

I agree, but I'm not sure that a trade course (a.k.a. vocational curriculum) would be sufficient. If the aim is to uphold standards and methodologies similar to those in engineering fields, then it's gonna require a curriculum of a similar caliber. In most science vs. engineering fields, a science degree is 3-4 years long, while a engineering degree is 4-6 years long (and often, add a year or two of internship/junior work). Of course, given the primitive state of software engineering science as of now, it might be hard to create a comprehensive curriculum deserving of the "Engineering" label.

That said, if you just want to be a …

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

First of all, if you are just inspecting the vector, you should pass it by const-reference instead of by value, to avoid an unnecessary copy, i.e., use this:

int computer::findMin( const vector<int>& v )
{
    int minIndex = 0;
    for( int i = 1; i < v.size( ); i++ )
        if( v[ minIndex ] > v[ i ] )
            minIndex = i;
    return v[ minIndex ];
}

(and the same for findPos())

As for finding the next smallest element, well, that depends on what exactly you want to do. Do you want to find the N smallest elements? Or do you want to just find the second smallest element?

If you know the smallest element, you can always find the next smallest element by passing it to the function and finding the minimum that is greater than that last minimum value. Here is a good start (not completely correct):

int computer::findMin( const vector<int>& v, int lastMinValue )
{
    int minIndex = 0;
    for( int i = 1; i < v.size( ); i++ )
        if( ( v[ i ] > lastMinValue ) &&
            ( v[ minIndex ] > v[ i ] ) )
            minIndex = i;
    return v[ minIndex ];
}

If you want to find the N smallest elements in one pass, you need to keep a record of those N elements as you go along. Typically, you would put the N first elements into the record, and then, each time you find an element that …

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

You need to provide both a const and non-const version of your operator[], as so:

class matrix
{
  //..

    float& operator[](int i);
    float operator[](int i) const;
};

//..

float& matrix::operator[](int i)
{
    return M[i];
}

float matrix::operator[](int i) const
{
    return M[i];
}

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

That's an interesting question. I would tend to disagree with your assessment.

Let me just rebut some of your specific statements:

If you reason with science, technology and Engineering, you will understand that science deals with the study to understand whereas technology devices ways to use those theories and observable techniques, and then with the blueprint set, the engineer builds on the technologist's ideas/technology.

As an engineer, your categorizations sound very odd to me. I think that what you call "technology" is actually "engineering", and what you call "engineering" is actually what a technician does. Here is a bit of standard terminology.

Fundamental science is the pursuit of knowledge for knowledge's sake, e.g., think of the theory of relativity (by Einstein). Applied science is the pursuit of knowledge towards some foreseeable application, e.g., think of the photoelectric effect (also by Einstein). That's not to say that fundamental science discoveries don't have applications, but only that the applications are not the primary focus of the research. And of course, actual scientists can be anywhere between those two extremes.

Engineering is the pursuit of concrete technologies and designs by applying scientific knowledge. It basically picks up where the applied scientists leave it. For example, creating image capture sensors (CCD or CMOS) by applying the photoelectric effect. There are three main kinds of engineering work. Engineering research (or eng. science) is about going back to study the scientifical principles in order to gain a more …

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

No it's not correct.

(1) The "conio.h" header is old and often not even supported at all, and it is certainly not a standard header. Also, you are not using any functions from that header, so you should just remove that include.

(2) The "stdio.h" is not a standard C++ header, it's a C header. To include the C++ equivalent of that header, you need to do #include <cstdio>.

(3) If you are going to use standard functions (like printf() or rand()) with pre-pending them with std::, then you need to add using namespace std; at the beginning (after the include statements).

(4) You need to care more about indentation than that. Please indent your code correctly, for everyone's sake.

(5) The rand() function is from the cstdlib header, so you need to add #include <cstdlib>.

(6) The rand() function needs to be seeded to produce actual random numbers, otherwise, it will always produce the same sequence of numbers every time you run the program. You can seed it with the srand function, as in the reference example.

(7) The variable max_x_coord is undeclared. This should be either some number or constant that is the maximum value that you want x to have, because rand() % max_x_coord will generate a random number between 0 and max_x_coord, whatever you put there.

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

Batteries have different environmental problems (toxic waste rather than CO2 & air pollution)

I don't think that's quite accurate. The recent battery technologies used (mostly NiMH for hybrids, and various Lithium-based systems elsewhere) are not actually "toxic waste", because they are mostly non-toxic, except for some exotic metals in their integrated electronics (like any other electronic device). They are recycled mostly to (1) make a profit (cheaper than mining), and (2) avoid the environmental impact of mining. With the older technologies (NiCd and Alkaline), they are indeed toxic waste and need to be recycled or otherwise disposed of properly, but these technologies are being phased out in favor of the modern alternatives.

jwenting:
And those are extremely high for the mining and processing of the materials needed for the batteries in hybrid cars.

AD:
How much different is that then the pollution caused during normal car manufacturing?

Well, it's true that mining and processing of materials that go into batteries can have a significant environmental impact (which is one of the main motivations for recycling them), but you have to keep things in perspective here. Mining for almost any kind of mineral has a significant impact. There isn't really a dramatic difference between the main constituents of batteries and common metals used in many other applications. This depends a bit on the exact chemistry used in the battery, but most of the materials are actually very common and used in all sorts of very …

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

Sounds to me like some kind of ear infection. You will probably need to see a vet if it persists or gets worse. It's hard to tell with infections cause some can just go away pretty quick while others can get real bad real quick.

As far as I know and can recall, dog ears are not supposed to be smelly (unlike bad breadth, which is pretty typical). But then again, I don't remember ever smelling my dog's ears, specifically.

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

Oh... I assumed the OP meant "install process" as in the process of installing Ubuntu itself. If the OP is talking about a CLI solution to install software onto a Ubuntu system, then, yeah, like rubberman said, you use apt-get for that, as in $ sudo apt-get install some-software-package.

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

I believe there are options to use a command-line interface for the installation, but of course, the default is the graphical "step-through" interface for doing the installation. Is there a reason why you don't want to use the GUI installer?

Ubuntu only seems to provide command-line installation for its alternate installations, that is, the server version or the minimal version (no graphics by default). This is probably because, for a "normal" desktop installation, there is really no point in avoiding the GUI installer. And if the installer's GUI doesn't work (the graphics driver has a problem), then you should verify that your graphics card is supported and all that before attempting to carry out the installation (this is because if the GUI installer doesn't work, it's unlikely that graphics will work out of the box once you install it, and you will have to do some work (in command-line only) to get it to work, and it might never work, so, do that research ahead of time).

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

is valid? I ask because I'm wondering what will happen to the returned result when ret (its owner) gets destroyed. I think it might be undefined behaviour.

It is indeed undefined behavior (UB). But, remember, "everything works fine" is still one possible behavior when you have a UB situation, along with a ham sandwich popping out of your USB plug. Undefined is undefined, anything can happen. Although this code is UB, it is very likely that in most situations, it will work correctly because the deleted memory (that the returned pointer points to) is probably not yet overwritten or reclaimed by the OS immediately after you have returned from the function. But on some platforms (or sporadically), this could lead to real problems (access violation / seg-fault, heap-corruption, etc.).

This whole situation is really the reason why we don't use these kinds of primitive constructs (C-style strings) in production code. You need to use some kind of RAII class for any dynamically allocated memory like that, such as the std::string class. And if you have to use such primitive devices, you have to do as Labdabeta found out, passing in a buffer to store the output (along with a max size for that buffer) to have at least some minimal guarantee of correctness.

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

i have no idea what goes on with my class since they have put me a higher level that i was supposed to be.

If you are not able to do what the class requires, then you shouldn't get a passing grade for that class. That's the whole point of grading or passing / failing classes. Why do you think you are entitled to pass a class without being able to do the work it requires?

Does anyone know any sites to send the hw (free/paid) that will help me?

Those two things are contradictory, because giving you a ready-made answer for your homework is not going to help you. We certainly do not condone this here.

We are happy to help with specific problems you are encountering with your attempt at solving the homework problem by yourself. In other words, you have to show your efforts to solve the problem, and we can provide some assistance (or hints) to help you along, but we will not do all the work for you.

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

It wasn't me who down-voted that post. But I can understand why: (1) just one line of code with no explanation is not very helpful, (2) the code is indeed wrong (undefined behavior), and (3) the corrected version of that code (Kristian_2's version) is still problematic due to overflow problems.

The reason why b = a + b - (a = b); is wrong is because of the order of evaluation of the parameters. The first "a" appearance (left-to-right) in that statement could just as well evaluate to the original value of "a", as it could evaluate to the new value of "a" (which is "b"). The code works if you assume that the first "a" appearance is evaluated to the original value of "a". But there is no guarantee that this will be the case, i.e., it is undefined behavior (UB). It's basically the same problem as with (++i + i++) which could evaluate to just about anything.

Also, even if it wasn't undefined behavior, it is still a swap method that requires additional storage, because a temporary variable must be created (by the compiler) to store the original value of "a" while it is being assigned a new value, and so, the equivalent code would be int t = a; a = b; b = t;, which is the traditional swapping method using a temporary variable.

And the reason why Kristian_2's version is also problematic is because it cannot work for all numbers, due to overflow. If both …

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

Are you talking about the xor-swap trick? Like this:

void swap(int& x, int& y)
  x ^= y;
  y ^= x;
  x ^= y;
};
rubberman commented: Elegant. The question is whether 3 xors is more efficient than one stack operation and 3 assignments... Probably! :-) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You need to show us the cpp files, and the command you used to compile them.

The linking errors that you get are telling me that there is no definition for your set_thresholdfinedflb global variable, and that there is no definition for the OnReceive() function. When you have a global extern variable declaration in a header file, you need to have a corresponding global variable definition in a cpp file. A global variable definition is simply this:

setthresholdfinedflb set_thresholdfinedflb;

(without the "extern" keyword)

As for the OnReceive function, I guess it is missing from your cpp file. But I don't know that. It might have the wrong signature, or its missing the class-name (as in void CsocketDlg::OnReceive(), if you are missing the CsocketDlg part, then the compiler will assume you are just defining a different function (non-member function) called OnReceive).

It might help you to read my tutorial on C++ compilation mechanics to better understand how everything comes together.

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

When you're the "big fish" in the pond, it makes business sense to just swallow up all your smaller competitors. Buying out your competition is the oldest trick in the book, all big companies do it all the time. That's just the normal way capitalism has always operated (capture, consolidate and monopolize).

I think its more interesting to notice the companies that Google is buying. They are clearly up to a lot more than meets the eye. They aren't just buying out smaller competitors, they have been buying their way into new territories (robotics, bio-tech, finance, tech. hardware (as opposed to software), etc.).

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

A tent and a rental car seems like a decent plan if you mostly aim for natural settings. Also, for the occasional city visits, sleeping in a hostel (youth hostel) is a very good option too. It's usually very cheap (20-40$ per night), if you are not too high-maintenance (which I don't think you are, from what I gathered). In hostels, you often meet people who are, well, interesting (for better or worse).

And if you are going to sleep in a tent in those areas, remember that in the desert climate like California or Nevada, the days are quite warm (e.g., 30C - 35C), but the nights can be quite shilly (e.g., 10C - 15C), so be prepared for that. On my first trip to California, I just brought light summer clothing, and I was freezing my a$$ off as soon as the sun went down.

Other than that, I don't have much else to say. Have a nice trip!

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

But no other province constantly threatens the rest of the country with separation.

No other major province was conquered.
No other province was forced to be part of Canada.
No other province has an empty underline where a signature should be on the constitution.
No other province has had repeated military actions against its people by the federation.
No other province has suffered segregation for the better part of its history, based on language and religion.

And you complain that we threaten to separate... I must ask, who's the whiny baby?

My mother's side of the family is French-Canadian; they moved from Quebec to BC three generations ago.

Ever wondered why they moved away? Three generations ago, living in Quebec as a French-canadian wasn't exactly all roses and peaches. You were essentially condemned to be poor, shackled by the catholic church and the English political and business classes. Even if you spoke good English, with an accent, the only way you could hope to move up in the world was to move as far away from Quebec and its segregated class system.

In fact, my community recently had its annual "Festival du Bois": http://www.festivaldubois.ca/

Sounded like a cool event! (I love the bottine souriante guy, Yves Lambert)

The one thing that struck me as a bit odd was this "Dîner en Plaid". Why did they choose to translate only half of the sentence in French? They could have …

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

Of course, it will require recoding it for Mac. But the copyright (or likely future patents) on the feature is not about the code itself, it's about the feature (how it looks, how it works for the user, etc..). There has been a raging war of software patents lately, especially by the big players like Microsoft and Apple to try and prevent people from reproducing their features in other (possibly FOSS) software (see smartphone patent war, which probably explains the unexpected switch to Windows Phone by some manufacturers (are they looking to avoid lawsuits from Microsoft? I think so..)). I think that this patent war is terrible.

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

Well, since he can't sell anything that is GPL-based (like most of what was brought in from Ubuntu in making the derivative). My guess is that either:

1) Apple has threatened him with a big law suite because he "copied" the Mac OSX features. And now, he is trying to save face by saying that he made a deal with "some big company".

2) He added a nice feature to PearOS that Apple was interested in applying to Mac OSX. As long as that new feature is entirely his creation (no code from others), then he is free to withdraw its FOSS distribution within PearOS, and instead license it to Apple, which would mean a big pay-out for him.

I hope it's the latter.

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

You neatly list the case where it is not appropriate in a typical use of a list, certainly not in the type of list I had allured to, mainly the case where you have thousands of list most of which are empty. In what circumstance would you encounter typically this? In a hash table, the list being used to deal with collisions.

I guess you have something specific in mind, and if you can justify your choices, then great! No harm done in raising questions.

Generally, I despise linked-lists. Every time I've included them in the possible options for some performance-sensitive code, the comparative benchmarks releaved that they were by far the worst choices. At this point, I've pretty much given up on ever using them.

I use linked-lists sometimes in non-performance-critical code when I want a self-managing list (i.e., just the chain, not the top-level class), which is also why it's used for hash table buckets.

Anyhow, I'm just not very impartial when judging linked-lists.

So, if your application is for buckets of a hash table, then why would you not just use the chain of nodes, without the "list" class, as it is normally done.

I thought you might have another trick that would allow me to have a policy with / without size without using multiple inheritance (because of vs2013 lack of EBCO) and without using my recursive inheritance which up to now still remains the only way to do this when there are …

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

I have been fine-tuning my recursive inheritance to the point that I can simply define the class I want to insert in the inheritance chain simply like this:

    template <typename...T> 
    struct policy_name: T...{
     // code here
    };

But... that's not a recursive inheritance solution. That's the multiple inheritance solution. There must be some kind of a confusion here.

What I would idealy like is simply use existing structures and type:

 inherit_recursively < existing_struct_1, existing_struct_2 /*,etc*/ > my_policies

where existing_struct_1 are plain vanilla structure such as:

 struct my_policy{
      // code
 };

Well, assuming you are aiming for a multiple inheritance version, then, you can use the technique I demonstrated a few posts back. It went like this:

template <typename... P> struct policies;

template <typename P, typename... T> 
struct policies<P, T...> : public P, 
                           public policies<T...> { };

template <typename P> struct policies<P> : public P {};
struct policy12 {
    // code...
}

// repeat for all desired policies with appropriate code

// and use like this:
policies<policy12, policy24 /*etc...*></policy12> my_chosen_policies;

That gives you exactly that effect, except that it doesn't implement the recursive inheritance scheme.

For a semi-recursive version, this might be the best approximation:

struct NullTerminatingTrait {
  template <typename... Tail>
  struct bind { };
};

template <typename... Args>
struct AnimalTraits;

template <>
struct AnimalTraits<> { };

template <typename T, typename... Tail>
struct AnimalTraits<T, Tail...> : T::template bind< Tail..., NullTerminatingTrait > { }; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Actually they are very real indeed. It is part of the core of what I am writing now. Were the things you wanted to point out what followed (mostly the nested EBCO) or is there still another useful trick in your bag ?

No, the things I was referring to were not the things I mentioned afterwards. So, here they are.

Firstly, the idea of not keeping track of the size of the list is just really quite terrible, for these reasons:

  • That information comes essentially for free, i.e., a simple increment on insertions, and decrement on removals.
  • The memory cost of storing the size value is a constant cost (O(1)) on the container's size, which is already the size of two pointers (head, tail) and of the state of the allocator (if any), adding an integer to that is not a big deal (also, as long as it's within a single cache line (usually 64 bytes), size doesn't really matter). The only case where that memory overhead would matter is if you had a large number of small lists, in which case, you would never use a linked-list in the first place.
  • Finding the size of a linked-list through traversal is so terribly inefficient (it thrashes the cache) that you would be better off disabling any size-query functions if the size is not being tracked.
  • If you are using an ID instead of a pointer for the "next" node, then your allocator (pool) would have to …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

1) There is a discussion on interfaces.

The technique (any special name for it?) you are proposing is the way to go

This technique is generally called type erasure. In this context, you could also call it "non-intrusive run-time polymorphism". A nice demo of that is "Inheritance Is The Base Class of Evil (it starts simple, but ramps up beautifully).

you seem to think that multiple inheritance is not a good way for multiple interface

Multiple interfaces are not a good idea to begin with (caveat: in that statement, I'm not including interfaces that refine each other (e.g., LivingBeing -> Animal -> Mammal -> Canine)). And when you do have to implement multiple interfaces in a single class, multiple inheritance is a really problematic thing to deal with, it's too intrusive (i.e. "locks up" the design too much, and you always have to dread that diamond).

In effect, your technique trades memory for an extremely minimal decrease in execution speed (creation of wrappers)

The wrappers do not, in general, impose any overhead. It's all washed away by the compiler. The wrapper just tells the compiler "do this dispatching dynamically", and it does so. The only overhead that will remain is what is necessary to accomplish the dynamic dispatching (object indirection and a virtual table lookup), which is what you would get anyways if you had virtual functions directly in your original class (i.e., that's just the price of dynamic dispatching).

The only …

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

Also, one of the real problems here is that there is no progressive representation for federalists. I know a lot of anglophones in Montreal who are very progressive, but would never vote for a separatist party. So, the farthest they can go to the left of the political spectrum is the liberal party, which is center-right (and I'm being gentle here). There is no NDP-like party in the provincial scale. This skews the results in majority anglophone areas in favor of the PLQ, and make it seem like all anglophones are very conservative, when in reality, they're not.

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

6) A great use is not for policies (other than vs2013 repair) but for multiple virtual interfaces that I can simply chain to avoid completely the cost on structure size! That (very useful) use remain even if I switch compiler.

I'm sorry, but I fail to understand how this could be useful at all. Let me setup a simple example scenario, let's say we are writing a library to represent different kinds of animals. Then, we could have a number of "policy" classes (or virtual interfaces, or whatever you want to call them) for different actions that animals do:

struct Walker {
  virtual void walk();
};

struct Runner {
  virtual void run();
};

struct Crawler {
  virtual void crawl();
};

struct Eater {
  virtual void eat();
};

struct TailWagger {
  virtual void wagTail();
};

// ...

So, under normal (OOP) circumstances, you could do this:

struct Dog : Walker, Runner, Eater, TailWagger {
  // ... dog-specific code (if any) here ...
};

And then, you could have Dog objects act polymorphically inside functions like this:

void wagTailThreeTimes(TailWagger& tw) {
  tw.wagTail();
  tw.wagTail();
  tw.wagTail();
};

int main() {
  Dog d;
  wagTailThreeTimes(d);
};

Now, using your solution for a recursive subclassing, you could re-implement the above using an approach like this (or a variant of it, which all boil down to the same thing):

struct NullTerminatingTrait {
  template <typename... Tail>
  struct bind { };
};

template <typename... Args>
struct AnimalTraits;

template <>
struct AnimalTraits<> …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

We don't do people's homework here. You show us what you have done, and where exactly you are stuck, and we can help you along. That's it. Doing your homework for you is not going to help you.

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

I guess I have to say something...

Right now, the elections are boring the heck out of me. I usually am pretty interested in them, but this was the first time I couldn't manage to watch through the entire official debate.

There's the CAQ party (Coalition Avenir Québec) with their single-track, right-wing rhetorics, i.e., reduce taxes and the government "bureaucracy" is to blaim for everything in all areas.

There's the PLQ party (Parti Libéral du Québec) with a complete lack of any kind of original thought, it seems they just want to sit on the throne and collect their brown envelopes from the Montreal mafia families.

Then, there's the PQ party (Parti Québécois) that tries to look sort of progressive but with no real substance, their strategy has always been to throw a bone here and there to appear to care about X or Y issues, and can't shut up about the charter or the referendum.

And finally, there's the QS party (Québec Solidaire) that is truly progressive, with lots of good ideas and a comprehensive plan. But they can't get elected, and probably won't win seats beyond a few "hip" boroughs in Montreal.

It's just a really boring campaign overall because the party with substance (QS) doesn't get coverage, the CAQ party gets lots of coverage because they have no substance but have good sound-bites that they repeat over and over again (and it's getting really old), and the main parties are just being their good old boring selves.

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

The correct code is this:

void StrVec::free()
{
    if (elements) {
        for_each(elements, first_free, 
            [this] (std::string& p) { alloc.destroy(&p); });
        alloc.deallocate(elements, cap - elements);
    }
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It has a major useful feature: if the subclasses have virtual function you only get a single vtable!

That's a good point. I didn't think of that. To have a single vtable pointer you need a single inheritance chain.

So is there a way where we could benefit both from the virtual fct memory shrinkage AND absence of repetition of code?

To be honest, I'm wondering why you would want policy classes to have virtual functions in the first place. I can hardly think of a reason why that would be useful, and even less so within your original solution, since you can't use the policies as polymorphic base-classes anyways (due to the varying tail-end of the inheritance chain). I think you need to give me a use case for this, because it makes no sense to me otherwise.

Given that this requires a single inheritance chain, it's pretty hard to get unique instantiations for each policy, since they need to be inserted somewhere in that chain. Therefore, each policy will always depend on the tail-end of that chain (that it inherits from).

So, I don't think you can really have it both ways.

However, you might be able to avoid virtual functions by implementing the dynamic polymorphism externally to the policy classes. My tutorial on this subject might enlighten you.

And also, is there a way to get EBCO with vs2013?

Ask Microsoft. But don't get your hopes up, they've ignored …

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

Neat piece of code!

However, there is one major problem. The problem is that each individual policy (where you have the code) will be instantiated for every unique combination of P... packs. For example, if you have these two instances in your code:

policies<policy12, policy24> my_policies_1;
policies<policy24, policy12> my_policies_2;

you will have the following template instantiations generated by the compiler:

struct policies<policy12, policy24> : public policies<policy24> {
  // code for policy12
};

struct policies<policy24> : public policies<> {
  // code for policy24
};

struct policies<policy24, policy12> : public policies<policy12> {
  // code for policy24
};

struct policies<policy12> : public policies<> {
  // code for policy12
};

You see, the problem is that, here you have repeating instantiations of the same code, for no reason (i.e., the repeating code is not instantiated differently at all). This is wasteful, and will lead to code-bloat and longer compilation times. This is the real tricky part with using templates in this way, you have to carefully analyse the generation of instantiations.

Here is a way to fix that problem:

template <int... P> struct policies;
template <int P> struct policy;

template <int H, int... T> 
struct policies<H, T...> : public policy<H>, 
                           public policies<T...> { };

template <int H> struct policies<H> : public policy<H> {};

enum { policy12, policy24, policy56 /*etc..*/ };

template <>
struct policy<policy12> {
    // code...
}

// repeat for all desired policies with appropriate code

// and use like this:

policies<policy12, policy24 /*etc...*/> my_chosen_policies;

The above …