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

It's all a matter of balance and common sense. If you look at most threads on this forum and others, and the rules of this forum, clearly we don't condone giving away complete ready-for-submission code. But if after several posts back and forth between the OP and a few users, working its way towards a solution to the problem, and explaining the issues the OP has difficulty with along the way, it often happens at the end that you could pick the code posted on thread and copy-paste it into a homework submission of your own.

First, as far as the OP is concerned, the important thing is the learning process that led to this final working code, and whether a portion of the code provided by users (even a significant portion of it) ends up on his homework / assignment submission or not, isn't really a big issue.

Second, for those who go out on the internet looking for ready-made code that they can copy-paste for their particular homework assignment, well, I doubt that they will have any trouble finding it, whether or not we post working final code on this forum. In fact, many of the basic assignments you would get in an introductory course on C++ are the kind of simple problems whose solution can often be found as easily as looking up the examples on www.cplusplus.com, so it's not like they have to look very far. The main thing is, you are …

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

>> Any ideas on how I can get this program to actually run??

Reading the error messages and going to the line that they point to and take a look at them. Maybe it's just me, but I think this might be a good start to getting the program to run.

Generally, when code is posted on a forum like this, it gets posted to explain it as an example. The hope is that it will help people understand how to do it on their own.

If working code is all you care about, try this:

#include <cstring>
#include <algorithm>

const int STRING_BUFFER_SIZE=80;//increase this to allow for really long names
struct Individual {
    char firstName[STRING_BUFFER_SIZE];
    char lastName[STRING_BUFFER_SIZE];
    char cityName[STRING_BUFFER_SIZE];
};
bool isGreater(const Individual& a, const Individual& b) { 
  int result; 
  return ((result=std::strcmp(a.cityName, b.cityName))?(result>0):((result=std::strcmp(a.lastName,b.lastName))?(result>0):(std::strcmp(a.firstName, b.firstName)>0))); 
};
void bubbleSort(Individual* a, int aLength) { 
  for(bool swapped=true; (swapped && (!(swapped=false))); --aLength) 
    for(int i=1;i<aLength;++i) 
      if((isGreater(a[i-1],a[i])) && (swapped=true)) std::swap(a[i-1],a[i]); 
};

Try submitting this and watch your grade shrink! (or sky-rocket, if your teacher is a moron)

There's a big difference between exemplary (pseudo-)code, working code, and production code.

Labdabeta commented: That is the coolest implementation of bubble sort I have ever seen! It makes your point nicely. +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>> When do I really need to use Delete in Destructors?

When your class is responsible for allocating the memory that a pointer points to, then it is also responsible for deallocating that memory. This is what is referred to as ownership.

If your class creates a dynamic array, or a dynamically allocated object, or an array of dynamically allocated arrays or objects, in other words, if you use 'new' in your constructor, then you must use delete in the destructor to deallocate that memory.

You can save yourself all this trouble by making use of "scope-based resource management" (or RAII for "Resource Acquisition Is Initialization). Classes like std::vector and std::string are examples of array-like RAII classes, and classes like std::shared_ptr and std::unique_ptr are examples of RAII classes that wrap a pointer (i.e. otherwise called a "smart-pointer").


>> I've been told every time I use new, it stays in memory even when out of scope and that I should use delete to remove it.. so do i need to do Delete P?

Yes. new is an operator to do a manual allocation of memory. If you allocate memory manually, you must deallocate it manually, with delete . Whatever piece of code allocates the memory, that piece of code (class, function, module, etc.) is responsible for deleting it in due time. Smart-pointers can be used to attach some automatic deallocation behaviour to the pointer, so that you don't worry about it down …

triumphost commented: AGAIN! Thank you and Lerner Both exactly what I wanted to know! +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This article is a pretty good recap (note, the table extends to the right with the rulings). It seems both the NY district court and the Federal court ruled in favour of open-source license-givers. I think they were both settled out-of-court later during an appeal (that's a common strategy, to defend through the lower courts and then, when facing a losing battle, to settle out of court before the appeal to a higher court goes through).

>> Settlement does not prove anything about the validity of the license.

Yes, but the point of a license is not to win a court case, it's to get your copyright recognized, and thus, get reparation in case of infringement. If the license is strong enough to lead to settlements, then it is strong enough for most purposes.

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

>> Am I stealing if I translate it?

Technically, yes. Kind of hard to prove though, if you do a reasonable job of changing names and syntax. Of course, assuming the algorithm's definition is public domain (appears in a text-book or scientific publication), it's OK to make your own implementation of the algorithm. It might be hard to distinguish your own original implementation from a translation of another (at least, hard to prove that its a translation and not an original work). But, if the algorithm is not public domain, then it's the complete opposite (hard to prove that you came up, on your own, with the same algorithm).

Overall, you have to consider the fact that implementations of well-known algorithms or methods are hard to defend against license violations, and probably, nobody would care to do so because there's no "idea" being "stolen".

>> What are the actual laws on copyrighting code

Basically, the same as most other things. First of all, there is a difference between a license and a copyright. GPL and others are licenses, which are pretty much a statement of a permission (with limits and rules that are agreed to by the parties, the "license agreement") that you give to others. When you are the author of original work, you automatically hold the copyright to it. So, if you don't attach any license to your code, it's implied that nobody has any right to copy or redistribute it, period.

If …

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

>>i am sorry i had just tried the code i paste before in vs2010 c++

Ha.. trying out the code can have deceiving results. When we talk of "undefined behavior" (or "unspecified" or "implementation defined"), it doesn't mean that running it will trigger the apocalypse. Of course, on a given compiler (and the options given to it) and on a given computer, you will get some behavior (even one that is predictable and repeatable). The important thing is that the behavior is not reliable if you ever consider changing compiler, its options, or platform.

The lesson is, if you are unsure of what a weird piece of code is supposed to output, trying it out on a compiler might not be the best way to figure it out. I would generally recommend searching reliable sources, like Bjarne's FAQ, Marshall Cline's FAQ, Herb Sutter's GOTW, www.cplusplus.com, the C++ Standard Document, and.. well.. me!

>> and it worked as i said please try it

No point, trying out code with undefined behavior on various compilers is a meaningless exercise.

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

@mazzica

int ansPre=v2 + v2++ + v2++ ;//execute line then inc so res =8 + 8 +8

This is wrong. The postfix increment operator does not perform the increment after the line is completely executed. It performs the increment where it appears in the expression, however, the result of the expression is the original value.

I reiterate my equivalence code:

int post_increment(int& i) {
  int result = i;  //record the value of the variable _before_ incrementing it.
  i = i + 1;       //increment the variable 'i' by 1.
  return result;   //return the value recorded before the increment.
};

The expression:

int ansPre= v2 + v2++ + v2++;

is equivalent to:

int ansPre= v2 + post_increment(v2) + post_increment(v2);

Which, actually, has undefined behaviour due to the fact that there is no rule, in the standard, to prescribe the order by which the operands of an expression are evaluated. So, the possible results are (also note that the addition is right-to-left associative):

int ansPre = 8 + (8 + 9);    // (a)
int ansPre = 8 + (9 + 8);    // (b)
int ansPre = 10 + (8 + 9);   // (c)
int ansPre = 10 + (9 + 8);   // (d)

There is no telling what your compiler might produce as a result. This is the same reason why there is no way to tell what ( i == i++ ) will give, neither could you tell what ( i == ++i ) would yield. …

triumphost commented: Ahh I was confused until I read this =] Trick Exam question! Thanx :D +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The post-increment operator ++ will increment the variable by 1 and return the value of the variable _before_ the increment. In other words, the operation is semantically equivalent to:

int post_increment(int& i) {
  int result = i;  //record the value of the variable _before_ incrementing it.
  i = i + 1;       //increment the variable 'i' by 1.
  return result;   //return the value recorded before the increment.
};

In light of the above, it comes to no surprise that the first result prints out 3.

You could rewrite the code, in more details, as follows:

int ans = 0;
    int v2 = 8;
    int v1 = 5;

    //ans = v2 % v1++; .. is equivalent to:
    int v1_original = v1;  
    v1 = v1 + 1;   // v1 is now equal to 6.
    ans = v2 % v1_original;  // the modulus is taken with the original value of v1.

    cout<<(ans);                    //This prints out 3..

    // cout<<(v2 % v1++); .. is equivalent to:
    v1_original = v1;   // v1_original is now equal to 6.
    v1 = v1 + 1;        // v1 is now equal to 7.
    int ans2 = v2 % v1_original;  // modulus with original value.
    cout << ans2;  // This prints out 2..  ( 8 % 6 ).

    cin.get();
    return 0;

It is important to understand the difference between the post-increment and pre-increment operators. The preincrement ++i will return the value of the variable _after_ the increment. The post-increment i++ will return the value the variable had _before_ the …

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

So.. what's the compilation error message? At what line?

I would probably try to pass in a function pointer instead, since "gset" is an array of function pointers, maybe try to define the "compute" function as:

double compute(double (*f)(double x), double i)

The rest can remain unchanged.

Also, as a matter of habit, you should avoid using a goto statement, because it is generally considered bad practice and off-putting for any programmer who might look at the code. Especially in this case, it is easy to avoid it with:

while(true) {
 
        cout << "Input Please: ";
        cin >> input;
        cout << "Function Please: ";
        cin >> function;
 
        ans = compute(gset[function-1], input);
        cout << ans;
 
    };

Also notice how the indentation makes it clearer that this is a loop. Even if you use goto-statements, you should indent if you can.

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

Have you learned about struct ? If you did, you should define a struct to hold all the data in once record, as in:

struct Individual {
  char first_name[80];
  char last_name[80];
  char city_name[80];
};

The kind of multi-level sorting that you are describing (sort by city, sort by last-name within a city, then sort by first-name within one city and one last-name) can be easily achieved with a proper comparison function. This is just like sorting things in alphabetical order (first sort by the first letter, then by second letter within each first letter group, etc..). There is no need for the type of triple sorting that Labdabeta (or is it Lambdabeta!) is suggesting, it would be very wasteful to do this.

Basically, you should define your own comparison function. I suggest:

bool compare_individuals(const Individual& a, const Individual& b) {
  int result = strcmp(a.city_name, b.city_name);
  if( result != 0 )
    return (result > 0);
  result = strcmp(a.last_name, b.last_name);
  if( result != 0 )
    return (result > 0);
  result = strcmp(a.first_name, b.first_name);
  return (result > 0);
};

The above uses the function strcmp which will return 0 if the strings are equal, -1 if the first string comes before the other in alphabetical order, and 1 if the first string comes after the other in alphabetical order. If you look at the above function, you will see that it is going to return "true" if individual "a" should go after individual "b" in the sorted array, …

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

I would guess the error comes from line 77-78 which reads:

return !temp1;
			return VIP = false;

which will, of course, never set VIP to false since the function returns before that line.

Also, you should update the setBal() function such that it also checks for a negative balance and sets the VIP value accordingly. It is very important in OOP design to make sure that the internal state of your object is always consistent (what we call the "class invariants"), that means, everywhere where the balance could change, the VIP flag should be updated too (that's why it's important to have only one set-function for the balance, and update the flag within it).


BTW, your poll question is flawed, you are missing the correct C/C++ answer which is a compilation error: "an rvalue cannot appear on the left-hand side of an assignment operation".

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

You need to have a variable like that "count" variable within the outer for-loop to count the number of inversions in the inner loop. At the end of the inner loop, you display the result, like cout << size[z] << " has " << inner_count << " inversions." << endl; , and then you add that to the global count, as in count += inner_count; .

Btw, there is an error in your code, at line 22, it should be if(size[z] > size[x]) (notice the "z" instead of "a").

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

The standard reference site is:
www.cplusplus.com/reference

A wiki site also exists:
http://en.cppreference.com/w/cpp

Otherwise, look to the C++ standard document (latest draft before ISO standard):
n3242

Another good reference is the FAQ lite.

You can also find several example codes here.

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

The stencil buffer is just a part of the framebuffer (which is the image that is rendered to the screen). The framebuffer is basically an image whose pixels are defined by different values, like red, green, blue, alpha, depth, stencil, and others. Obviously, RGB stores the color, Alpha stores the transparency, Depth stores the "distance" to the screen, and the stencil is just an additional value that is available to the programmer to store anything else he might want to store on a per-screen-pixel basis.

I don't know much about making shadows, and my knowledge of it goes back many years ago, so I really don't have much more to say about it.

Maybe this tutorial will be more helpful and current than NeHe's tutorial.

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

Making shadows in OpenGL (or DirectX) is not a trivial task. I'm not surprised that you would have trouble with the NeHe tutorial on the subject. The important thing to understand is that, in order to determine the shadows that the objects will cast, you need to render the scene from the perspective of the light point. If you look at a scene from the point of view of the light, everything that makes it to the "screen" is a surface that is lit by the light, everything that doesn't is covered by a shadow (at least with respect to that light source). So, the basic idea to create a shadow in OpenGL is to first render the scene from the point of view of the light source, and generating masking textures from that rendering pass. Once you have the masks, you blend them (by multiplication) with the surface textures of your objects and render the scene in the final point of view (camera).

Obviously, the technical details of how to do this can be complicated, it traditionally involves using the stencil buffer to record the masking texture. I'm not sure what the state-of-the-art is on this subject. Many modern multi-pass rendering and scene graph rendering employ render-to-texture capacities of most modern GPUs.

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

First of all, you cannot create an array whose size is not fixed at compile-time. So, your array "size" cannot be a static array of size "n", you need a dynamic array. In C++, the preferred way to create a dynamic array is to use a standard class called "vector". So, you would do the following:

#include <iostream>
#include <vector>   // include the "vector" library.
using namespace std;

int main() {
  // the code to get the value of 'n'
  // then, create the vector of size n:
  vector<int> size(n);
  //.. the rest of your code..
  return 0;
};

Then, you must know that indices for arrays in C/C++ are zero-based, meaning that the first element in the array has index 0, and the last element in the array has index n-1. So, you should not do a for-loop as for(int j=1;j<=n;++j) , but you should do the for-loops as for(int j = 0; j < n; ++j) . This is a general rule for all array-like things in C/C++, indices are always starting from 0.

Finally, you are somewhat on the right track when it comes to your last loop. However, you will need a nested loop, i.e., one loop inside another. This is because you are iterating through all elements, and for each element you need to iterate through all remaining elements. Typically, this would look something like this:

for(int i = 0; i < n; ++i) {
  for(int j = i; j < n; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The problem is that you are not doing a deep copy of your object. Your assignment operator performs a shallow copy (copy only the pointer, you don't copy the memory it points to). I suggest you read my tutorial on resource-holding classes and RAII. Your copy-constructor is also wrong, I highly recommend that you use a copy-and-swap idiom, like I recommend in my tutorial.

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

>> 1. How do I check the Template's parameter type?

Using typeid is one way to do it, but a rather unusual one. It is more common to use one of the multiple type-traits that are provided by the <type_traits> library (C++11 only), and/or the ones provided by Boost.TypeTraits. As a simple example:

template <typename T>
T square_value(T value) {
  if( boost::is_complex< T >::value )
    return conj(value) * value;
  else
    return value * value;
};

The more useful type-traits include checking if the type has cv qualifiers, checking if it is convertible to some other type, to check if it is a pointer type, or reference type, etc... It is rather rare that you would want to check for one specific type, unless what you really want is to have a specialization (or overload in the case of function templates) for a given type.

Two other useful techniques are the BOOST_STATIC_ASSERT and BOOST_CONCEPT_ASSERT . In the first case, you can just check a condition at compile-time, like BOOST_STATIC_ASSERT(( typeid(T) == typeid(int) )); which will fail with a reasonably error message if the condition is not met. In the second case, you can assert that a given type satisfies a certain "concept", meaning that it can be used in certain ways, like BOOST_CONCEPT_ASSERT(( boost::CopyConstructibleConcept<T> )); to check if the type is copy-constructible for example.


>> 2. How do I restrict the Template's parameter to a specific type only?

There are …

jaskij commented: you sir, owned me +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If Unity is the only problem, install another distro that is based on ubuntu, I recommend Kubuntu. Xubuntu seems popular too, or Mint.

To get the best drivers, the easiest is just to make sure you have the latest version of a distro (and kernel). For the interface or desktop environment, it's a matter of choosing the distro that you like best, and some, like Kubuntu, are very highly customizable.

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

I understand what you mean, the Unity desktop is weird to say the least.

Have you considered a sister distro. I recommend Kubuntu 11.10 (which has KDE as a desktop environment). I always liked it better than Ubuntu, maybe you will too. The plasma desktop is very customizable (you can layout the menus and task-bars and all in any way you like).

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

I don't know what wiki you are referring to, but the code-blocks wiki has pretty detailed instruction on doing debugging in code-blocks.

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

If you are using an IDE to do your programming, then most decent IDEs have a debugger included in them. The basic way to use a debugger is to set a break-point (a point in the code at which the execution will be suspended). Then, you run the program until the break-point and then step through each line one by one. Between each step you can usually evaluate the variables (local variables, arrays, etc.) to see if they have the value they should have at that point. See your IDE's documentation or help or tutorials to find out how to do these things (set break-points, step through lines of code, and evaluate variables).

If you are not using an idea and don't have access to this type of debugger, then do as WaltP suggested: just print out all relevant information at all relevant points in your code, run the program and inspect the output to see if it makes sense and where it goes wrong.

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

You're question is, by itself, a good topic for a software project. You exposed a problem that I cannot solve, maybe you can create an algorithm that solves that problem. The task you have bestowed unto us is this:

Input: No information whatsoever about your interests or skills!

Required output: A good title for a software development project!

Get my drift?

We don't do random-project-title generation here. However, you'll have more luck on this site.

If you want output, you need to provide useful input!

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

First things' first, to a large extent, classes in the C++ standard libraries (with the exception of iostreams) are not object-oriented classes, they are not meant to be derived from and they generally don't derive from other base classes from which you could also derive. The iostream library is an exception as it provides an OOP architecture with specific classes that are base-classes from which classes like std::ifstream or std::stringstream are derived, and these base-classes are indeed intended (possibly) to act as base-classes in user-side code (meaning you are "allowed" to derive from these classes). std::string , which is actually just a typedef for the class std::basic_string<char> , is not meant to be derived from or treated as a base-class in any typical OOP sense of the term. It does not (or at least not according to the C++ standard) have a virtual destructor or any other virtual functions for that matter. This means one thing: you will not get polymorphism from inheriting from this class. This is very important, because inheritance is (mostly) about dynamic polymorphism (polymorphism in the OOP sense). To a large extent, if inheritance does not give rise to a polymorphic use of your class, then inheritance is not necessary or useful, and should not be considered a good option.

Is it dangerous? Yes and no. If you assume that you can override existing functions of the string class or have polymorphic pointers to the class (when it actually points to the derived class), then …

WaltP commented: I stand corrected. Thanks. +17
StuXYZ commented: Superbly argue, thx +9
triumphost commented: YOU!!! Always giving me the best answer =] +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, Boost.Thread has the future / promise mechanism, that's where it was taken from. What std::async accomplished under-the-hood to run a thread with the given callable and attaches a future to it is quite simple, at least for the non-deferred launch version. The deferred version is also quite simple to implement in boost.

If you look at the two examples of using a packaged_task / future from the Boost.Thread documentation page, you will find exactly two examples: one async and one deferred (or lazy-future). If you need to give parameters to the function, just use boost::bind . You could even wrap all this in a async() function template that exactly replicates the standard one, it's easy.

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

Indeed, pretty much all modern operating systems have good mechanisms to deal with memory and use the hard-drive if necessary. Of course, there will always be a chance that you run out of memory (whether the OS doesn't want to take up more HDD memory or because you run out of HDD space). So, there is really no need for you to write code that does this type of thing, and the OS will do this much better than you can ever hope to. For instance, the OS will swap memory between the RAM and HDD such that your program is always working on RAM memory (the chunks of memory not currently used are basically sleeping on the HDD). This is a kind of mechanism you would have a really hard time doing yourself.

As for the new operator, the C++ standard prescribes that it must throw a bad_alloc exception if you run out of memory, so that is entirely platform independent. If you want the "return NULL" behaviour, you must use the no-throw new operator, as in new(nothrow) int[1024];

If you are going to be working with large chunks of data, it might be a good idea to consider a container like std::deque which stores the complete array as a number of big chunks of data, as opposed to one contiguous array. This will generally be less demanding for the OS because the OS won't have to make space for one huge chunk of memory. …

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

Well, from the code you posted, if there is no delete a; after, then there is clearly a memory leak there. How I found that memory leak: I opened my eyes and looked, that's a good trick.

Seriously though, finding memory leaks can be a very difficult if you have a large code-base to plow through.

One great tool for this is Valgrind. I think VS also has decent tools for that, but I haven't tried them.

All in all, the best remedy for memory leaks is prevention. For instance, designing software with ownership relationships in mind.

Another, somewhat desperate, trick is to just make a file-search for the keyword "new" and for each one, make sure it is either immediately wrapped in a smart-pointer (with automatic storage) or that it has a corresponding "delete" (and that any deep-copy or reallocations clean up the old storage correctly).

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

Once you understand the idea that the purpose of a programming language is to act as an interface between a human being and a computer, then it becomes pretty clear why goto statements are bad. A guy that is trained to write assembly code might have a brain that is closer to that of a computer than a human being.

Looking at the standard, except for the two small sections that explain what goto and label are, and the uses of goto to explain what under flow control constructs do, all the mentions of goto relate to the types of ill-formed code they can cause. This involves jumping across code that creates objects and jumping in or out of try-catch blocks. Another, more important issue is the non-linearity that they generally introduce in the code. A for-loop is easy to explain, run the statements from start to finish and do it again for X number of times. Code that is expressed as a number of loops and conditional statements is fairly easy to follow logically. A spaghetti code of goto statements, or careless jumping around is much harder to follow and thus much more error-prone (forgetting to handle a particular condition, losing track of values of variables, and so on).

It is true that a good programmer, especially one used to working with assembly code, will be able to mostly avoid those pitfalls when writing the code, but that is a very weak defense of gotos for one …

zeroliken commented: well said +9
Labdabeta commented: Nice Answer! +4
MrEARTHSHAcKER commented: Another great explanation +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You're loop is a basic linear search. You go through each element to find a match for the given value. When you do find a match (line 150), you set a bool to true to signify that the match was found. However, you don't stop the loop. It will continue to loop around till the end of the array, which is not only useless but wrong. At the end of the loop, you check the bool and if you found a match you return the location of that match, but since you always iterate to the end of the array, that returned location will always be at the end of the array, that's wrong. At the very least, you need to stop the loop, and break is the C/C++ keyword to do that.

An even better way to do it is simply like this:

// Method to search the list for the first instance of the given item.
 template <class T>
 int Array<T>::search(const T& itemFound) const
 {
		 for(int location = 0; location < size_; location++)
		 {
				 if(elements_[location] == itemFound)
				 {
						 return location;
				 }
		 }
		 return -1;
 }
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

At line 103, you should have elements_= new T[rhs.size]; (notice "int" changed to "T").

In you copy-constructor, it is not a good idea to name the parameter copy because there will be a name conflict with std::copy that is used in the same function. And you should qualify the call to std::copy in full, not just copy .

At line 152, you need to break out of the loop. So, insert a break; statement just after line 152.

In your assignment operator, you should check for self-assignment with a simple if( this == &rhs ) return *this; statement at the beginning.

You write std::cout << int_array1 << std::endl; in your test program, but you haven't created an overloaded function for the << operator and your Array class template. So, you should add, within you class template declaration, something along the lines of:

friend
  std::ostream& operator <<(std::ostream& out, const Array<T>& rhs) {
    for(int i = 0; i < rhs.size_; ++i)
      out << rhs.elements_[i] << std::endl;
    return out;
  };

In the future, if your question is about compilation errors, you should provide the error messages and mark the specific lines to which your compiler points you as being the faulty ones.

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

>> If I store a node per cell at the same (or similar) resolution as my heightmap then isn't this just a grid representation using waypoints?

Yes. Why would that be so terrible? You probably would use a down-sampled resolution visa vi your heightmap (like half the resolution, so some resolution that makes the distance between waypoints reasonable compared to the size of your characters).

>> I was hoping to achieve something more like the large triangular polygons that I have seen for the majority of navigation mesh examples.

That's very reasonable. This won't be any harder or easier to construct versus a "square" grid. And, it will probably yield somewhat nicer results (less squarish paths). Here is a quick piece of code that would do exactly that:

#include <boost/graph/adjacency_list.hpp>

#include <cmath>

//Create a struct for node-properties:
struct WaypointProperties {
  double x, y, z;  //store the position.
  double value;    //store the desirability value.
};

//Create a struct for edge-properties:
struct PathSegmentProperties {
  double travel_distance; //store the distance traveled along the edge.
};

// Define the type of the graph:
typedef boost::adjacency_list< boost::vecS,  //Edge-list storage type.
                               boost::vecS,  //Vertex-list storage type.
                               boost::undirectedS,    //Connection type
                               WaypointProperties,    //Waypoint properties
                               PathSegmentProperties, //Path-segments properties
                               boost::vecS            //In-edge-list storage type.
                             > NavigationMeshType;

const double half_tan_30 = 0.5 * std::tan(M_PI / 6.0);

double get_distance(const WaypointProperties& p1, const WaypointProperties& p2) {
  return std::sqrt( (p1.x - p2.x) * (p1.x - p2.x)
                  + (p1.y - p2.y) * (p1.y - p2.y) 
                  + (p1.z - p2.z) * (p1.z - p2.z) …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Can you please tell me what is meant by forward declaration?

A forward-declaration is just a way to tell the compiler that there will eventually be a class declared later in the code. It is only a means to stop the compiler from complaining that it doesn't recognize the type or class. Of course, this is only temporary, the actual declaration of the class has to appear eventually (if it is ever used). When there is only a forward-declaration available so far (as the compiler is looking through the code), you only can do very limited uses of the class in question. Because the compiler doesn't know what that class is, only that it is a valid class, you cannot use any of its member functions or anything, you cannot create an object of that class, you cannot have data members of that class or inherit from it, all you can do is declare pointer / reference parameters or data members to an object of that class. Forward-declarations are typically used when you have two classes that depend on each other (and in other more advanced cases). Here is a simple and typical pattern that involves a forward-declaration:

class Cat; // forward-declaration.

class Dog {
  public:
    void ChaseThisCat(Cat& someCat);  //use of forward-decl. to declare a reference parameter.
};

class Cat {
  public:
    void FleeFromThisDog(Dog& someDog); 
};

// Now, Cat has been declared and can be used to implement the member function of Dog:
void Dog::ChaseThisCat(Cat& someCat) {
  //... …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, I guess I should answer this, considering that path-planning is the subject of my Ph.D. thesis (the scenario is quite a bit more complex, of course).


Storage:

What you refer to as a "navigation mesh" is essentially a graph (a network of nodes and edges that link them together). Associated with each node, you would normally have information like its position in the environment (2D, 3D, or more, in my research its 15 dimensions) and other information that is usually useful to determine the desirability of that position (like proximity to obstacles, proximity to some goal position, exposure to enemies to dangers, etc.). Associated with each edge, you would normally hold information like the traveled distance/time or other cost-of-travel values.

Now, once you understand that your navigation mesh is in fact a graph. You have to look into graph theory, which is a huge deal in computer science due to its many applications, namely, the internet! (which is also a graph or network). There are many kinds of graphs with different properties and different storage methods.

Generally, a path-planning problems over a fixed graph (or mesh) will involve a grid-like graph, which, in formal terms, is a planar and undirected graph.

In concrete terms, this also means that when looking for an actual implementation or method of storing your navigation mesh, you need to be looking for a "graph library". The most prominent and one of the best graph library …

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

Pretty much everything that you find documented at www.cplusplus.com/reference, that's most likely what the competition will want you to stick with. If anything, they might allow the new (extended) set of standard libraries from the C++11 standard, which you will find described and listed in the draft that deceptikon linked to.

In between, there is also the TR1 libraries (Technical Report 1) which are basically the same as the additions that were made into C++11, but they appear in the std::tr1 namespace. You will find decent reference for them on the msdn page.

Also, you might want to double-check with them about this, because sometimes people colloquially talk about "standard libraries" in a way that includes not only the actual language-standard libraries, but also the native OS libraries like Win32 API libraries or POSIX libraries, and some might also accept libraries that are simply very widely used and recognized like Boost and other well-established libraries like OpenGL, SDL, libxml2, etc... So, you might want them to clarify what they mean exactly, because if they give challenges that are anything more than pure algorithmic, console programs, then it's impossible to use only standard libraries... Never mind, I checked the website, it doesn't seem like they would ask anything that would require more than basic algorithmic programming (read a file, run an algorithm, and spit out the answer).

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

Interesting question, it warrants a detailed response. So, let me address some issues before providing more concrete solutions.


>>I have started finding lots of uses for abstract classes to define interfaces for common functionality using polymorphism

RED FLAG!! Maybe you misspoke, because otherwise you are hinting at a very common mistake, what I call "derived class intersection" meaning that you take different concrete classes that your software already has (or that you have in mind) and you find things that they have in common (i.e. the intersection of the functionality sets) to lump them into some base-classes (as in, having base classes with the common functionalities). This is a problem for many reasons. Mostly, it is a problem with the design methodology that will have bad consequences going forward. The proper design methodology involves assessing the requirements that an algorithm or data structure imposes on the objects on which it must operate, and then, create abstractions that lump related requirements together as a base-class or interface or other things (see later). Then, you can create concrete (or final) classes that fulfill those requirements and thus, implement the abstraction / interface. The point is, the choice of functionality that should make up an interface should be solely motivated by how this object is intended to be used by the algorithms or data structures. What functionalities turn out to be common between different derived classes is irrelevant in the design of your base classes or interfaces. Down the …

Kanoisa commented: Very clear and descriptive, thanks +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yeah, that's pretty much it. Try this for instance:

#include <pthread.h>
#include <iostream>

void* f(void*) {
  for(int i = 0; i < 1000; ++i) {
    std::cout << "Print from the Thread!" << std::endl;
    usleep(1000);
  };
  return NULL;
};

int main() {
  pthread_t threadID;
  pthread_create(&threadID, NULL, f, NULL);
  for(int i = 0; i < 1000; ++i) {
    std::cout << "Print from the Main Function!" << std::endl;
    usleep(1000);
  };
  pthread_join(threadID, NULL);
  return 0;
};

Compile with:

$ g++ pthread_example.cpp -o pthread_example -lpthread
wildplace commented: cool! i love your example! +3
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your function and its output are correct.

If you consider the interval to be inclusive [start, end], then inverting the sequence [1,4] should produce the output AEDCB (because 4 is the last element).

If you consider the interval to be non-inclusive of the end-point, as in [start,end), then you should just call your function with end - 1 .

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

For GUI programming, it is pretty much as easy to do it in C++ as with any other language, it is not a matter of the language but of the GUI library (or package) that you use. For a long time, under Windows, main-stream GUI programming was with MFC which was terrible in whatever language you used, but it was even worse in C++. This had the consequence that a lot of programmers used to write GUIs in VB and wrap all the important code inside DLLs written in C++ or C (because VB is terrible for anything except really simple stuff, like the code behind most GUIs). However, there are other GUI packages, like Qt (Nokia) and VCL/CLX (Borland), which are really easy to use in C++ (even for a while, Borland's VCL was called "the VB-killer" because it made programming GUIs in C++ even easier than in VB, which would have made VB entirely irrelevant at that time, it survived only due to inertia).

Today, the picture of GUI programming has leaped forward (or back) due to the .NET platform. Essentially, the new GUI system that Microsoft is trying to impose on the world pretty much rules out the use of pure C++ programming (because .NET requires a managed environment with reference semantics, which is deeply incompatible with C++). So, you have to use one of MS's proprietary language (VB.NET, C#, F#, J#, C++/CLI) to use .NET. Another, non-MS, viable option is Delphi which works also for …

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

It's actually simpler than you think (for once!). To do a partial template specialization in C++ you simply leave the unspecified template arguments in the template declaration and put them in the class name... well, that sounds weird, so let me just put it in code:

// This class-template has 2 arguments <T,Number>.
template<typename T, int Number>
class Data {            // This class-template is a general template 
                        //  because 'Data' appears unspecified (just 'Data').
    T Array[Number];
  public:
    T& operator[](int);
};
      
template <typename T,int Number>
T& Data<T,Number>::operator[](int element){
  return Array[element];
};


//this class template has only one argument <Number>
template <int Number>
class Data<double, Number> {    // This class-template is a specialization of 'Data' 
                                //  because 'Data' appears specified as 'Data<double,Number>'.
    double Array[Number];
  public:
    double& operator[](int);
};
      
// The member function of Data<double,Number> is simply as follows:
template <int Number>
double& Data<double,Number>::operator[](int element){
  return Array[element];
};

Once you understand the logic behind it, it's quite simple to understand. And the fact that template arguments are types or integral values, or even template template arguments, doesn't make much of a difference.

So, it's as simple as that keep the unspecified arguments in the template declaration ('template < .. >') and specify the other arguments in the class-name (while filling in the remaining arguments with the new template arguments).

You can actually do much more interesting things once you understand how this all works. For instance, these are also a valid partial specialization:

template <typename T, int Number>
class …
MrEARTHSHAcKER commented: Great effort to explain some advanced concepts :D +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yeah sure, here's an example:

#include <boost/random/linear_congruential.hpp>

#include <boost/random/uniform_01.hpp>
#include <boost/random/normal_distribution.hpp>

#include <iostream>
#include <ctime>

int main() {
  boost::random::rand48 rng = boost::random::rand48((unsigned int)time(NULL));

  std::cout << " This is a random number: " << rng() << std::endl;

  boost::random::uniform_01<double> udist;

  std::cout << " This is a uniformly distributed 'double' value in range [0,1]: " << udist(rng) << std::endl;

  boost::random::normal_distribution<double> ndist(0.5, 0.25);

  std::cout << " This is a normally distributed 'double' value with mean 0.5 and std-dev 0.25: " << ndist(rng) << std::endl;

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

Quicksort is not really the most popular algorithm for sorting. The most popular algorithm for sorting is whatever sorting function your programming language's standard library provides, that is, if you consider "popular" as what most people use. In C++, we use the std::sort() algorithm (and other sorting-related STL algorithms). And the std::sort() function is probably implemented in a way that is very close to the Introsort algorithm. Quicksort is often cited as a popular method because of the C function qsort() which I doubt is actually a vanilla quicksort implementation, probably also closer to an introsort method.

So, quicksort is the basis for most sorting algorithms implemented in standard libraries. But none actually just use quicksort in its basic or vanilla form because its not stable. The problem is mainly that quicksort has so-called "pathological cases" and plenty of them. This means quicksort is generally fast at O(NlogN) with a low constant factor due to its simplicity, however, its worst-case performance is O(N^2) which tends to occur often (depending on the actual original layout of the values in the array you are sorting, i.e., pathological cases). Because of that, actual implementations have a lot of other safe-guards, micro-optimizations, back-up methods (heap-sort), and things like that to avoid really bad performance in the pathological cases. Then, there are all kinds of additional issues (like minimizing swaps, minimizing comparisons, having better locality of reference, etc.) which complicate the matter even further.

If you want a comprehensive study and …

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

The destructor also doesn't delete the pcMyString data, that's a memory leak.

The reverseString() function is marked "const" when it is clearly (from its name) a function that would modify the contained string.

The pointer "poMyOld" is public and uninitialized. It is generally bad to expose a pointer as public because you can't control what it points to, and thus cannot implement any reliable strategy to make sure it doesn't leak memory or corrupt memory.

If the purpose of the first constructor is to copy the string "oOld.pcMyOldString", then it doesn't do that job at all.

The parameter of the first construction should probably be sent by const reference, not by value.

The parameter of the second construction should be const, unless the intent is to modify the object.

As AD said, the shallow copy that is performed in the second constructor is very very bad. You need to do a deep copy.


You ask what are the errors in this code. I don't see any compilation error in the code, but the amount of coding errors is quite astounding. In fact, there are fewer correct lines of code in that piece of code than there are erroneous ones.

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

I think enough time and ink has been spent on this already, so let me lay out a clearer, step-by-step explanation of this circular-queue implementation.

You have to first examine what you need those "rear" and "front" indices for.

The rear index is used to find the next available free slot in your array, in order to enqueue a new element. So, it is natural that the "rear" index should be the index of the first free slot immediately following the last occupied slot in the array.

The front index is used to read the value of the first occupied slot in your array, in order to dequeue it. So, it's natural that the "front" index should point to the first occupied slot in the array.

Then, doing the "wrap-around" in the array is a simple matter of applying a modulus operation. That is, you increment the index, and then you apply a modulus with the size of the array which will cause the index to wrap back around to 0 when it reaches the end of the array. There is no need for a conditional statement to check the "end" condition, and applying a modulus instead is way more efficient too.

So, at the very least, your enqueue and dequeue functions should be:

void enqueue(int n) {
  queueArr[rear] = n;  //fill the first empty slot with value n.
  ++rear;              //move rear to the next empty slot.
  rear %= SIZE;        //wrap-around with a modulus. …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The main problem you will have with STL's priority-queue is not the efficiency, but the fact that it provides no means to update the priority value of elements already in the queue. This is an operation that is required in A* (at least, the last time I checked).

If you take a look at the Boost.Graph Library's implementations of A* and Dijkstra, which both are just thin-wrappers for a Breadth-first visitation algorithm, use a custom priority-queue implementation. This priority-queue is called d_ary_heap_indirect which is a D-ary heap implementation with an indirect priority value, but most importantly, it includes the necessary update() and push_or_update() functions that STL's priority-queue lacks.

The STL's priority-queue will be faster for more simple operations (just pushing and popping) because it is a relaxed heap (giving constant-time pushing). But, for more dynamic operations, I recommend BGL's d_ary_heap_indirect implementation. Better, yet, you could just use the BGL's A* and Dijkstra implementations.

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

>>But I am not able to figure out from those discussions.

That's probably because of two reasons that make this question a bit hard to answer. Before getting into it, of course, the two standard options that are available are C standard functions (i.e. fread() and fwrite(), or fscanf() and fprintf() for formatted IO), and the C++ standard functionalities (the <iostream> library). Otherwise, there are always OS-specific functions. The main difference between the two standard options is the amount of buffering done under-the-hood (buffering means that either data is pre-emptively read in blocks and cached before you actually demand it, or written data is accumulated before being actually written to the file in larger blocks). The C++ iostream library is designed with buffering mechanisms at its core, and as a result, implementations of it (provided by your compiler-vendor) generally have more sophisticated, multi-level buffering under-the-hood (and on top of any buffering mechanism that may be implemented by the OS). On the other hand, the C functionalities are generally just thin-wrappers for OS calls (so the only buffering done is that of the OS).

Buffering is the cause of the first complicating reason why there is no definitive and generic answer to your question. The amount of buffering needed for good performance and how the buffering is implemented depends a lot on the way that you read / write data. By that, I mean, in some applications you keep a file open and write small chunks of data once …

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

>>Do you mean if i were to declare an object with dynamic memory within a particular function it would be available within another function?

Yes, if you provide the pointer as a result of the function for example.

Generally, this is not recommended, but sometimes hard to avoid. If you do that, it is also recommended that you use a smart-pointer instead of a simple pointer (or raw pointer).

In concrete terms:

int* give_pointer() {
  return new int(42);
};

int main() {
  int* pi = give_pointer();
  
  // now, the value can be accessed from outside the function, through pi:
  std::cout << " The value is: " << *pi << std::endl;
  
  // now, here's the nasty part, you have to delete the pointer yourself:
  delete pi;  //But, what if it was created with malloc()? What if it was a static variable? This line could cause a crash...
  return 0;
};

Normally, you would, instead, provide an additional function to deallocate the object. The point of all this is that the life-time of the object is from point of the "new" call up to the point of the "delete" call, so, it is not bound to an automatic scope like local variables (which, simply speaking, are created when you enter the function and get destroyed when you leave it).

Better yet, you use a smart-pointer whose job is to delete the object when noone needs it anymore (this is what std::shared_ptr does).


Another use …

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

When you have syntax like g->total_nodes it means that you access the object pointed to by "g" and then access its data member called total_nodes .

When you write it as g.total_nodes it means that you access the data member called total_nodes that belongs to the object "g".

So, if you want the first version to work, i.e. the version with Graph g; , then you have to replace all the g-> with g. , because now, "g" is an object, and not a pointer to an object (like in your original code).

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

There are a few possibilities:

The ugly way: Use variadic functions from C. This is what you were referring to with the "va_list". You should know that the first argument does not have to be the count of arguments, it could be anything, but C variadic functions don't give you any other means to know how many parameters were passed, so you need to figure out some way to infer that (e.g. the printf() functions infer it from parsing the formatted string). This method is ugly because it is not type-safe, and it has limited application.

The new way: Use variadic templates from C++11 (the new standard). The new C++ standard has introduced a new feature called variadic templates which allow for variable number of parameters to function templates (where each parameter's type is templated too). This is both type-safe and will tell you how many parameters have been passed. Of course, you have to do a bit of template wizardry to write the function (and its overloads for different specific parameters).

The traditional way: Use default parameter values. Basically, this allows for variable numbers of parameters, but the sequence is fixed, and has an upper-bound, of course. For most cases, this is sufficient.

The Boost way: Use the Boost.Parameter library. This library is designed to make "packs" with the parameters of the function, allowing any ordering, naming them explicitly at the call-site, and default values, of course. This is …

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

One of the main reasons why autocomplete features are generally lacking in enhanced text editors (like Emacs or Kate) is that it requires some knowledge of the build configuration (source files included in the build, include paths, environment variables and such things). So, the bare minimum that you are going to need is an integration of a build-system into the text editor, and once you have that, it is pretty much an IDE.

The other reason why auto-completion is lacking in light-weight code editors is that a good and intelligent code-completion system is NOT a light-weight piece of software.

I don't know of anything that is like that, half-way between an enhanced text editor and a full-blown IDE.

Personally, I use KDevelop (for Linux, you didn't specify the OS). The code-completion engine it uses is really good. In my experience, I find that it outperforms even IntelliSense (the Visual Studio code-completion engine). KDevelop uses Kate to manage the text-editing part of the IDE (code-highlighting, auto-formatting, folding, and all that stuff), but it supplements it with code-completion and great support for external build-systems. I also write heavily templated code which usually is too much to handle for the code-completion systems of CodeBlocks, Eclipse, and Visual Studio, but, amazingly, the code-completion system of KDevelop is mostly able to keep up and resolve to good suggestions most of the time. KDevelop is a full-blown IDE (albeit a very light-weight one), and I don't know if there are any ways to …

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

>>Is there any way to add my own language to code::blocks

CodeBlocks isn't the best for this purpose, it is pretty much just designed for C++, afaik. For custom syntax highlighting and things like that, most enhanced text editors allow you to define custom grammars to be parsed and how the syntax should be highlighted, good candidates include Emacs and Kate.

As for configuring a different compiler, well I'm not so familiar with the CodeBlocks build system, so I can't say. But any decent build system will allow you to customize the compilation as much as you like, cmake is one such example of a build system which allows you to do just about anything you want (for example, I configured it to generate the doxygen documentation for my code, and before doing that, to update the time-stamps of the file-mod dates). Most build-system will allow that kind of pre-processing, launching shell scripts, special programs or commands, do some amount of parsing folders, files and file-contents.