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

Taking your code to the 21st century, and doing correct indentation (which helps understanding the code), we get:

#include <fstream>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <conio.h>

using namespace std;

int amountRead = 0,max_read = 99;
const int maxn = 4200;
float array[maxn] = {0.00000};

void getfloat();
void read();
float sort();

float sort()
{
  // you could also use the standard sort function:
  //sort( array, array + amountRead, greater<float>() );
  for(int i=0;i<amountRead;i++)      //prefer declaring 'i' in the for-loop.
    for(int j=0;j<amountRead-i;j++)  //prefer declaring 'j' in the for-loop.
      if(array[j]<array[j+1])
        swap(array[j], array[j+1]
        
  amountRead++; //what is this?

  ofstream outfile("sort2.txt"); //don't do open-close at each iteration.
  for(int i = 0; i < amountRead; ++i)
  {
    //if(array[i] != 0)  //this comparison is useless of 'float' variables, they are rarely exactly 0.
    //{
    cout << array[i] << endl;
    outfile << array[i] << endl;
    //}
  }
  //Where is the return value???
}

void getfloat()
{
  ifstream infile("sort2.txt"); //declare variables when you use them first.
  ofstream outfile("sort3.txt"); //don't open-close the file for no reason.
  float x = 0.0; //prefer local variables, try to avoid global variables when unnecessary.
  while(infile >> x)  //check the input at the same time as reading.
    outfile << x << endl;
}

int main()  //the C++ standard requires that main() returns an integer.
{
  ifstream infile("float.txt");
  while((amountRead < max_read) && (infile >> array[amountRead])) //invert the conditions to use the "short-cut" feature of '&&'.
    ++amountRead; //pre-increment is preferred in general.
  
  for(int i = 0; i < amountRead; ++i)
    cout << array[i] << endl;

  sort(); …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

OpenInventor is a pretty useful tool to make OpenGL programming easier by providing lots of built-in functionality.But there are many others.

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

Usually, I refer beginners to Marshall Cline's C++ FAQ page for general explanation of just about everything that is fundamental to C++.

>>actually that is the first time to know that I can invoke the constructor directly by this way.

It is not a direct invocation of the constructor. It is creating a temporary object, that's not the same thing. A constructor cannot be invoked directly (as a function call), it is always associated with the creation of an object (that's why it is called a "constructor", because it is used during the construction of an object).

I presume you are aware of this syntax:

int a(42);  //creates a local variable, of type 'int', called 'a', and initialized to '42'.

Now, if you just want to create a local variable but that is temporary (which means it does not need to have a name), than you just omit the name from the syntax, and get:

int(42);

Now, if you have a class that takes no parameters to one of its constructors (the default constructor), then the equivalent to the above for that custom class with default initialization is:

my_class();

That's about all there is to know about this. Don't know what else to say.

>>it seems an interesting topic for me

I can't be sure what "interesting topic" you are talking about. If you are talking about the above matter about creating temporary objects, then I can hardly see how …

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

>> it looks to me more like a function

Or like the construction of an object, which it is.

If I have a class named "my_class", I can create an object of that class with "my_class()", which means the object is default-constructed and doesn't have a name (a temporary). So, the "exception()" just creates a temporary object of class "exception" that is default-constructed. The "throw" keyword takes whatever you give it (e.g. object) and propagates it (or carries it) back to the first try-block it encounters, where it will attempt to match it to one of the catch-statements.

You need to provide the throw statement with something to throw, it is most usual to give it a temporary object since there is usually no point in creating the exception object before throwing it, but in theory you could also do:

try
{
   cout << "  Function throwException throws an exception\n";
   exception e; //create exception object.
   throw e;     // and throw it.
} // end try
catch ( exception & ) // handle exception
{
   cout << "  Exception handled in function throwException"
        << "\n  Function throwException rethrows exception";
   throw; // rethrow exception for further processing
} // end catch

But why take two lines of code to do what one lines does equally well:

throw exception(); //this is pretty much the same as above (but less wasteful).
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Just got the ball rolling with this first tutorial on the topic I find the most fundamentally improved in C++0x (and also one of the most important thing to "update" in old C++ code to make it C++0x-friendly). Hoping more will come.

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

Most of the errors are due to the fact that a unique character (as opposed to a string literal) has to be denoted with single quotes ' not double-quotes ".

So, lines 19 to 27 should look more like this version of line 19:

if(KeyPressed == 'I' || KeyPressed == 'i')  //notice the single-quotes 'i', not "i".

The rest of the errors are due to the fact that you use non-standard functions that are probably not present on your implementation.

If you want to learn by looking at example code, try to pick from more reputable sources. This example code is bad, non-standard, and old. It is no example to follow. Try the recommended sources.

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

>> i have problem compiling this code

Post the compilation errors. You may not understand them, but we do. It is hard to know the error, especially since you are using a lot of non-standard functions and headers (gotoxy(), randomize(), random(), clreol(), etc.).

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

cout is in the std namespace. You need to either qualify it fully, like so:

#include <iostream>

int main() {
  std::cout << "Hello World!" << std::endl;
};

Or, you can issue a "using namespace std;" statement, as so:

#include <iostream>

using namespace std;

int main() {
  cout << "Hello World!" << endl;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This FAQ site is likely to fill all the holes in your understanding, if you take the time to read through it. The page on references will help with the reference/pointer business.

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

Your expression "shapes - shapes[1]" takes the difference between the two pointers, not the two objects. You need to dereference the pointers before you apply the difference operator. As so:

*(shapes[i]) - *(shapes[1])

Also, I would suggest you make your operator - a friend function instead of a member function, as so:

friend float operator-(const Shape& lhs, const Shape& rhs)

This is preferred for all operators which are not required to be member functions.

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

Beginner's Guide to C++0x:
The Big Five - Implementing a Resource-holding RAII Class


This tutorial will show how to implement a resource-holding class showing practical use of C++0x features. A resource-holding class is any class which holds, with its data members, a resource which could include:

  • dynamically allocated memory
  • an internet connection socket
  • a file stream
  • any other handle to an operating system resource (e.g. window or thread handle), or
  • an opaque pointer from an external library.

The main characteristic of a resource-holding class is the requirement to allocate (or create) the resource (capturing a handle or pointer to it) and then releasing the resource.

This type of class is fundamental to practical programming because a C++ programmer will very often face situations in which low-level data structures are needed or when it is required to interface C++ code to external libraries (or APIs) which often provide C-compatible interfaces based on handles or opaque pointers ("opaque pointer" is a general term for a pointer which is provided via some API functions and should only be acted on (or dereferenced) from within the API functions, not by the user of the API, so, to the user, it is not really known to what it points to, and is thus "opaque"). The preferred strategy to handle these situations is to create a C++ class which wraps all those low-level functions and API calls, and provide automatic, encapsulated handling of those low-level details, hiding them …

mrnutty commented: Haven't read it al, but deserves recognition for the effort. +13
m4ster_r0shi commented: Very informative! +7
Tellalca commented: keep it coming +4
JasonHippy commented: Excellent tutorial on C++0x. Nice one! +9
happygeek commented: thanks for the tutorial +12
alwaysLearning0 commented: Cool!! nice start +4
sergent commented: Awesome!!! +4
WolfPack commented: Great work. Keep it up. +12
kvprajapati commented: + +15
Sky Diploma commented: ++ +9
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You probably need to use an external library of some kind.

FreeImage is one which is easy to use, supports most standard image formats and allows you to do some basic transformations on them.

If you want to do more advanced transformations on the image, then you can use OpenCV.

If you just want to display the image, then I would suggest you use a GUI tool to make an application with a graphical user interface. Qt is a very good option as a GUI tool and C++ IDE for it. Any GUI tool will have features to load images.

Another option is WinAPI, which supports Bitmap files. There are of course more advanced solutions from Microsoft as well, but they mostly require Visual Studio to use them.

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

>>to use even more stl,

To use even more STL, with C++0x:

#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>

int main () {
  using namespace std;
  std::vector< int > items;
  for (int i = 0; i < 25; ++i) items.push_back (i % 3);

  std::map<int,int> counts;
  std::for_each( items.begin(), items.end(),
    [&counts](int x) {
      if(counts[x]) {
        std::cout << "Number " << x << " appears " 
                  << counts[x] = std::count(items.begin(), items.end(), x)
                  << " times in 'items'." << std::endl;
      };
    }
  );
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The input works by reading words by ignoring any "space" character. Here, a "space" character means anything from an actual space, to a tab, or a new-line.

The reason why it outputs in one column is because there is a "endl" (meaning "end-line") printed after each word, that has the effect of putting each word on a separate line.

So, your intuition is correct. The input ignores the column-row structure and just reads one word after another (left-to-right, top-to-bottom). And the only reason for the one-column output, is the way it is outputted.

For instance you could re-output the same structure with this code:

#include <fstream>
#include <string>
#include <iostream>

using namespace std;

int main() {
  ifstream file_in("my_data.txt");
  string s;
  int i = 0; //count the number of words read.
  while(file_in >> s) {
    cout << s << " ";
    if( (++i) % 3 == 0 )  //make new line at every 3 word.
      cout << endl;
  };
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Or am i making this way harder than it should be?

Seems like a totally reasonable approach. But if you read one string at a time, the default behavior is to read a word at a time. Read each word, check for being "T" or "H" or other (invalid input), and fill your data-structure with the corresponding 0 and 1. Stop when your data structure is full or when you run out of input.

To read all words, you can do:

#include <fstream>
#include <string>

using namespace std;

int main() {
  ifstream file_in("my_data.txt");
  string s;
  while(file_in >> s) {
    cout << "Got word: '" << s << "'" << endl;
  };
  return 0;
};

The above program should print all the words contained in the input file.

I think that's a good starting point.

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

I think that your intent with the dm_energy_vec class was to just make an alias for the vector<float> type, this can be done with a typedef, as follows:

typedef vector<float> dm_energy_vec;

Then, all your code should work.

If you actually want to make the dm_energy_vec class more complicated (not just an alias for the vector of floats), then use firstPerson's solution.

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

Calling the destructor does not erase the object. It is just like calling any other member function on the object. What makes the destructor special is that it gets called automatically when the object is deleted. An object is deleted when the memory it occupies is freed. In the case of a dynamically allocated object (heap-allocated) using the "new" operator, the object gets deleted when you call "delete" on its pointer. In the case of a stack object (like a local variable), the object gets deleted when it goes out-of-scope (the block in which it was declared ends). So, the code you tried to write or expected to have done is:

int main() {
  {                // open a new enclosing block.
    Pig Jack;      // create a stack-based Pig object.
    Jack.Feed(20); // feed Jack the Pig.
  };               // Jack goes out-of-scope here, its destructor is automatically called.
  Jack.Feed(20);   // ERROR! 'Jack' was not declared in this scope.
  return 0;
};

Calling the destructor explicitly is not something you do normally. The destructor is always called when the object's life-time ends, but the destructor does not end the object's life-time, you just understood the causality relation in the wrong direction. Generally, an object has no control over its life-time, it is always the code (or class) that creates the object that determines when it gets destroyed (at least, that's how it should be). In C++, the code that creates the object, owns the object and is responsible for destroying it when …

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

As for the static_cast vs dynamic_cast, the only difference in effect between the two is that the dynamic_cast does a run-time check to see if the cast is possible. In other words, if you pass a pointer to class A, and try to cast to a pointer to B, then dynamic_cast checks, at run-time, that the pointed-to object actually is of class B (or any class derived from B). If you have another mechanism to make sure that the pointed-to object can be cast to this other type, then you don't need the run-time check that dynamic_cast does and then, static_cast is sufficient, correct and more efficient. So, there is nothing wrong with your code in that regard, you don't need dynamic_cast since you can already determine the actual type via this "type" data member.

It is indeed bad design to require such a function. You should try to find some sort of abstract functionality that your function does, and try to turn it into a virtual function in your base class A, which you can override for the special or additional behaviour required in B and in C. You should give us more details about why you are writing this function and these classes, because we need to know the functionality you are trying to implement to be able to help you find a better alternative.

The reason this is bad design is because you break several tenants of OOP, that is, encapsulation is broken because an …

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

To be able to separate the implementation from the declaration of a class template, you need to do a explicit instantiation of the class template for all the types you might need this class template for. This is very unusual when writing a class template, but possible.

If your school assignment specified to separate the implementation and the declaration, which is usual and preferred for non-template classes, then, are you sure it specified that you had to implement it as a class template? Know what your requirements are, because if it is to develop a class template and also to separate implementation|declaration, then it's a very unusual request.

Anyways, say you only need to use the class template for the type T = "int", then, in your cpp file, you can write the following statement after all the implementation of your functions:

template class List< int >;  //explicit instantiation.

If you need the class template for more types, you have to provide one such statement for every type you could possibly use your class template with. As you see, this is not a very practical solution.

The other alternative, if all you want is to have declarations in a header file and implementations in a cpp file, but you don't care that the cpp file be compiled on its own, then you can simple #include the cpp file at the end of your header file (within the include-guard).

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

You cannot (easily) separate the implementation and the declaration of a template. The compiler needs to have access to the implementation in order to instantiate the template for a given set of template-arguments. Read this.

Simply put all your implementations in the header file (either inside the declaration of the class template, or following it).

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

This forum is not a repository for posting homework assignment questions. We don't do your homeworks for you, it is not in your interest or anybody else's.

Try to solve the problem yourself, and if you have problems with specific things, post them back here, show your code that demonstrates your efforts to solve the problem, and it starts from there.

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

It gives the reason why directly above the function definition:

45   // utility function called by insertNode; receives a pointer
46   // to a pointer [B]so that the function can modify pointer's value[/B]

If you simply pass the rootptr, any modification to the root-pointer with the function will not affect the rootptr variable in the caller's code (insertNode).

A more usual way to do this is using a reference instead:

47   template< typename NODETYPE >
48   void Tree< NODETYPE >::insertNodeHelper(
49      TreeNode< NODETYPE > *& ptr, const NODETYPE& value )
50   {
51      // subtree is empty; create new TreeNode containing value
52      if ( ptr == 0 )
53         ptr = new TreeNode< NODETYPE >( value );
54      else // subtree is not empty
55      {
56         // data to insert is less than data in current node
57         if ( value < ptr->data )
58            insertNodeHelper( &( ptr->leftPtr ), value );
59         else
60         {
61            // data to insert is greater than data in current node
62            if ( value > ptr->data )
63               insertNodeHelper( &( ptr->rightPtr ), value );
64            else // duplicate data value ignored
65               cout << value << " dup" << endl;
66         } // end else
67      } // end else
68   } // end function insertNodeHelper

It makes the syntax cleaner, and it is essentially equivalent to the pointer-to-pointer version.

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

First of all, the istream iterator gets initialized at the line 18, and so does the end iterator (default-constructed iterator marks the end).

Second, the while loop simply iterates until begin reaches the end of the input. That is what the (begin != end) condition verifies.

Third, the *begin++ dereferences the begin iterator, and increments it (for the next iteration of the while loop).

Fourth, the words[s] finds an entry in the map associated with the string "s" (or *begin++ in this case). The values associated to the strings are integers, because of the declaration std::map<std::string,int> meaning that the map associates integer values to string-valued keys. Now, if the entry does not exist (that string has not been seen before), then the [] operator of std::map will take care of creating a new entry for that string, and the integer value associated to it will be default-initialized (or zero-initialized) meaning that it will have value zero.

Then, the entry gets incremented. So, every time a string is seen it will be registered in the std::map that keeps count of the number of occurrences of every word.

Finally, the reason why the words get separated when you output them at the end of the program is because std::map keeps all the entries sorted by the key (the strings), so it will appear in alphabetical order when outputted. And the reason why you get the whole sentence when you just re-output the values of *begin++ is because …

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

>>Well, that's far from the mature and though provoking response I've come to expect from you. I'm sorry I wasted your time.

I'm sorry you see it that way. For the most part, I agreed with you, only complemented with some caveats. It only turned ugly when replying to the insinuation that it is not "bad practice" to us C functions in C++.
Promoting or even defending the use of C functions or deprecated things in C++ does tend to make my blood boil. I do understand and accept people who say "I use them because I'm working on a legacy code-base", "I use them because I have used them for X amount of years and they are more familiar to me", "I use them because all my colleagues are mostly coming from C", or better (but unlikely) "I use them because I have strong evidence that they are faster than the C++ alternative". But implying that there is no gain in moving to more "pure" C++ functionalities, that's vitriol to me.

I frankly have no idea what you would have expected me to reply to that (and was quite surprise to see this coming from you). I could certainly not turn my reply into a thesis on "C++ coding paradigms and why they beat C like a rented mule", so I kept it superficial. But then, the example code you posted comparing C IO and C++ IO. That ticked me off bad, I really don't take …

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

I don't exactly understand your questions. Once a class template is instantiated, it is no different than a normal class. Once a function template is instantiated, it is no different than a normal function. A template is just a pattern to manufacture a type or function once the template arguments are provided. Once they are provided, the generated class or function is just like a normal function (except for a few "expert-level" details you don't have to worry about at this point).

I think these examples will answer your questions:

struct foo_normal {
  int value;
};

template <typename T>
struct foo_templated {
  T value;
};

template <typename Foo>
void bar(Foo f) {
  std::cout << f.value << std::endl;
};

int main() {
  foo_normal f1; f1.value = 42;
  bar(f1);  //will print '42'
  foo_templated<int> f2; f2.value = 69;
  bar(f2);  //will print '69'
  foo_templated<double> f3; f3.value = 1.61803399;
  bar(f3);  //will print '1.61803399'
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Sure, why would you not be allowed to? Are you talking about several functions with the same name (overloads). Then, yes, you are also allowed to mix function template and normal functions, even when overloading (but you should avoid specializing function templates if you provide other overloaded functions, that's the only caveat).

If that didn't answer your question, you might want to post some simple example of what you have in mind.

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

>>And of course, is it WORTH passing ints by reference?

Certainly not by const-reference. Ints, like pointers and references, are usually of the native word size of the computer, which is 32bit or 64bit on most PCs. So, making a new int variable (i.e. copying it) and passing it by value is not going to be more expensive than creating a new pointer or reference, storing the address of the int variable that was given as argument to the function, and passing that pointer or reference into the function. What could potentially be slower (depending on how clever your compiler is) is that every use of the variable within your function will require a dereference (explicitly when using a pointer, or implicitly when using a reference), this is an additional step that could slow things down a bit, however, compilers tend to be pretty clever at avoiding this if there's a better way.

About passing by const value, I guess you could say it's a bit controversial whether there is any benefit to it. But, I have been pretty satisfied with the arguments on the side of "it doesn't make the slightest difference", so I hold that opinion. The main argument is that a compiler can easily see, within a function, if you modify the value or not, as part of the basic optimizations it does, so marking as const isn't going to tell the compiler anything that it doesn't know already, so no optimization opportunity is created …

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

@Narue:
If we were to write a holy book for Daniweb's code goddess, it would describe this moment as:

And the Narue descended from the heavens,
and with a might display of wit,
like lightning ripping the sky,
she smite down the arrogant man.
Mere mortals shall be humble before their Goddess, she said.

Now, let me humbly reply..

>>How do you figure that? [old headers not working]

I have seen them not working. On BCB6, old C file IO's don't work under Vista (I had this painful problem some years ago), while the C++ iostreams work fine.

>>They're a part of the standard, so they're required to work "fully" on any conforming implementation.

Yeah, and all compilers are _required_ to support exported templates too, but only one compiler does. All compilers and all implementations of the standard libraries are delinquent in one way or another.

>>Why? [is it bad practice to use C functions in C++]

Oh.. come on.. now you're just trying to tick me off. You don't want me to do an "Inverse Torvalds Rant", do you? First off, you could hardly argue that it is "better" to use C functions in C++ when there is an equivalent solution using C++ standard libraries, at best, the two are equal. There are a certain number of idioms and design patterns that are very desirable in C++, and I know that you know most …

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

The ampersand & when appended to a type-name marks it as a reference. So, this type const Matrix& reads as "a reference to a constant Matrix", while Matrix& reads as "a reference to a Matrix", and Matrix is, of course, just a Matrix. If you pass a variable as Matrix , it is passed-by-value, meaning that the parameter will, in theory at least, be copied before the code enters the function. If the & is used, then you pass-by-reference, meaning that a reference is taken from the parameter (i.e. its address is taken) and passed to the function, it means that you don't cause a copy. If you have a parameter that is strictly an input parameter (you only need to read data from the parameter), and it is not cheap to copy it, then you can pass it by const-reference meaning that you don't copy the parameter, just pass a reference to it, but since you mark it as "const" you force yourself not to modify it and you also promise the caller of the function that his variable will not get modified during the function execution. If you want an input/output parameter, then, pass by reference (non-const). And passing as const Matrix (by value, but const) is not any better performance-wise than passing by non-const value.

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

>>You should write a beginner's tutorial on C++0x for Daniweb. That will be a great way to promote this site. I can also contribute on some easier topics!!.

That's a great idea! I think most advanced programmers can just look at the wiki or Bjarne's FAQ page, and totally understand how to use C++0x features, even from just the short and simple examples. But, for beginner to average programmers, there are still nice features to take advantage of. Something along the lines of "getting acquainted with C++0x and how it can benefit the average programmer". I'm thinking "auto", initializer_list, lambdas, rvalue-references, constexpr, range for-loops, decltype(), variadic templates, etc. I guess the new standard libraries should be tackled as well. It might be a lot of work, but it might be possible with enough contributors. If interested, I guess a good starting point would be to post some example C++0x code on this wiki setup by daviddoria. Then, it could be turned into one or more tutorials to go on Daniweb.

Narue, are you up for it?

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

Don't use the standard libraries with the .h extension, they are out-dated (pre-1998) and are only kept around for backward compatibility and I wouldn't expect them to be updated to work fully on newer implementations (OS).

Use the following headers instead:

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>

And it is bad practice to use C functions in C++. Use the iostream library instead of those old C functions (fopen, fwrite, fclose). Replace your code with this C++ equivalent:

void guardar_cliente(cliente x)
{
  std::ofstream f("data.txt", std::ios_base::binary | std::ios_base::out);
  f.write((char*)&x, sizeof(x));
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have a weird way to implement our suggestions.

First of all, you need header-guards. This is important to ensure that the same code does not appear twice, because if the compiler looks at the same code twice it will not like it, as it breaks a fundamental rule of C/C++, that is, the One Definition Rule (ODR), which states that you should not define something with the same name twice (type or function or variable or whatever), even if the definition is the same.

For some reason, you put this:

#ifndef vector // avoids loading vector again if it has been previously loaded

I guess the intent was to not #include <vector> twice. Not only is that unnecessary because the <vector> header, like any other header in any other library that is worthy to be used by anyone, has a header-guard, so double-inclusion is not a problem to be worried about, ever (as long as all headers that you create or use have a header-guard, which is pretty much a given in C/C++). Second problem with the above statement, is that it will #include <vector> after this line, no matter what. All directives that start with # symbol are pre-processor directives, meaning that they are processed before the (real) compiler looks at the code. The pre-processor basically ignores everything else and just processes the # directives (except that it also does a find-and-replace through the code for all the #define identifiers, like "#define X …

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

For structuring the games of the tournament, I would suggest you construct a separate tree-structure for the tournament games. For example, if you construct one game as follows:

class Game {
  private:
    Team* team[2]; //have two teams that are involved in this game.
    Game* next_for_winner; //the game that the winner would advance to.
    Game* next_for_loser;  //the game the loser might do (like a bronze-medal final).
  public:
    //..
};

Then, you construct a list of games, link them and initialize the teams for the first round of elimination. Say you have 8 teams in total, than you know there will be 4 quarter-final games, 2 semi-final games, and 2 finals (gold and bronze), that's 8 games in total (Number of games in a tournament with small-final is equal to the number of teams in total, if it is a power of two). So, you create 8 games (in a std::vector). Then you fill the first 4 games with the 8 teams, with whatever match-ups make sense in your program (like season standings, or preliminary round results). Then, you link the "next_for_winner" and "next_for_loser" pointers to the games that follow in the list, if there is no game to follow for the loser, or if it is a final, then you set the next game pointers to NULL. If there are yet no teams assigned to a game (results are not known yet, previous round is not completed), then set the team pointers to NULL as well. When you play a …

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

>>Hey mike the "-> bool" specifies a return type?

Yeah, that's the Lambda expression syntax.

It is also a new way to specify return types for normal functions, with the "auto" keyword. As so:

auto my_function() -> int {
  //..
};

This is especially useful for function and class templates where the return type can be contingent on the parameter types in a non-trivial way.

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

While you are using C++0x, then you might as well do:

my_list.remove_if( [](int x) -> bool { return x == 4; } );
Jsplinter commented: ah, right lambdas! thank you +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I would make a class to store all the information relevant to a team, with some member functions to manipulate that data. For example:

class Team {
  public:
    std::string name;
    std::vector<Player> players;
    int current_standing;
    //...
};

I would probably suggest you store the data in a std::map which allows you to access the elements by a key-value, for instance, the team's name. For example:

int main() {
  std::map<std::string, Team> teams;

  Team& t1 = teams["Patriots"]; //teams can be looked-up and created by name.
  t1.name = "Patriots";
  t1.current_standing = 1;
  //..

  return 0;
};

As for choosing a container, the image attached might help.

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

I agree with Narue.

Collecting a bunch of "fundamental" types into one header file is fairly common, as long as those types constitute a cohesive group of related types. The fact that you cannot find a better name than "types.h" sort-of hints to the fact that they do not form a meaningful cohesive group (btw, you will need a header-guard that is more specific than TYPES_H, otherwise you might have problems later). In theory, if you stick to the one-header-one-class rule, then this whole thing of circular dependency won't be a problem at all, but it certainly can seem a bit wasteful to have one header for one typedef. But again, if later you decide to make the GrassType a bit more complex (some user-defined class), then it will be more convenient if it is in its own header.

Collecting many types into one header can also cause great grief to the building process. The header file in question sort of becomes one file on which a huge amount of other files depend on. This means that anytime you change something to this file, it will trigger a complete rebuild of all code, including stuff that is absolutely not related to the change that you made. This can get really annoying at times, if the code-base is large. The more fine-grained your headers are, the less unaffected code you have to rebuild when small modifications are made.

But, definitely, the situation seems to mandate the use of …

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

>>don't see where u got rid of the tan Tan = cos#/sin#.. I don't see that anywhere

First of all, tan = sin / cos, not the other way around. I got rid of the tan^2 terms by noticing that everywhere the tan^2 appears, it is multiplied by a cos^2, which I distributed on the addition, and, of course, giving tan^2 cos^2 = sin^2. So the tan^2 turned into sin^2. Then I collected the terms again to reduce the number of flops to a minimum. This is high-school math, not rocket-science (and I've done rocket science). Getting rid of tan is important because tan can go to +- infinity (divide by zero), so if the tan is avoidable, then it should be, for sake of numerical stability.

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

>>"Memory is insufficient!" how can i fix it ?

Either get a computer with more memory (RAM) or figure out a way to solve your problem with smaller data-sets, like sub-matrices. You could split the problem into smaller matrices and solve the leastSquare problem for each smaller matrix. There is no easy solution to this.

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

You have one too many parenthesis on line 10, it should be:

float K5 = ((k0 * nu * pow(cos(lat),3))/6) * (1 - pow(tan(lat),2) + (esq * pow(cos(lat),2)));

Notice that there is no parenthesis just before pow(tan(lat),2) , this was causing the subtraction to distribute over the next term, thus, flipping its sign.

The priority of operations in C++ is the same as for regular math, so you don't need to abuse parentheses that much. You should also store intermediate values that require expensive computations, like cos and sin. And try to reuse previously calculated values as well. Finally, you should avoid using the pow() function for integer powers, it is more economical to expand the multiplication. With that in mind, you could have:

float cl = cos(lat); float clsq = cl * cl;
  float sl = sin(lat); float slsq = sl * sl; //pre-compute cos and sin.
  
  float K1 = M * k0;
  float K2 = 0.5 * k0 * nu * sl * cl;
  float K3 = (K2 / 12.0) * (clsq * (5.0 + esq * clsq * (9.0 + 4.0 * esq * clsq)) - slsq);
  
  float y = K1 + p * p * (K2 + K3 * p * p);
  float northing = y;

  float K4 = k0 * nu * cl;
  float K5 = (K4 / 6.0) * (clsq * (1.0 + esq * clsq) - slsq);

  float x =  p * (K4 + K5 * p * p);
  float easting = x;

I also eliminated the tan() in the equation, because tan() can be singular and it is generally a good idea to avoid it, and you always can through trigonometric identities.

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

With the parameters that you gave, this function will require more than 4 GB of contiguous memory to run. My guess is that you run out of memory. To test if this is the case, you should try this in your main function, instead of the original call to leastSquares:

try {
    surf.leastSquares(Pts, 3, 3, 7120, 7120);
  } catch(std::bad_alloc& e) {
    std::cout << "Memory is insufficient!" << std::endl;
    return 1;
  };
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>i have the program do n1[q=q+2] to find all numbers and put them into different variables.

That is not what the program does. That's my point. All your program does is pick two characters and transform them into numbers. It does not find all numbers, it does not even search for any number, it picks it from a predetermined position in the string.

>>And i use the for() statement to make sure that with it in my original program, i know it works.

The for() loop is inconsequential, if something works outside a loop, it works inside too.

You need to focus your efforts on what is important. What is most important is to find a way to detect numbers (where they start, where they end), and be able to figure out whatever is between numbers (like +).

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

Lets see what your code does, and clarify it.

int l = 1;
    for(l = l; l > 0; l--)

The statement l = l is useless, it does nothing. Replace it with the previous line.

for(int l = 1; l > 0; l--)

Now, it should be pretty obvious that this just execute once, so it is equivalent to:

int l = 1;

But you actually never use l, so you can just get rid of it.

Now for the body of the loop:

int q = -2;
    string n1 = "1+5";
    int n;
    int e;
    stringstream(n1[q=q+2]) >> n;
    stringstream(n1[q=q+2]) >> e;
      
    cout << n + e << endl;

It should be clear that n1[q=q+2] just evaluates to n1[0] and then n[2] . Clearly, this takes the first character and gives it to a temporary stringstream object, then does the same for the third character. All the stringstream does is convert that character to a number. If you only need to convert one character to one number, then you can do this on your own simply like this:

int n = n1[0] - '0';
    int e = n1[2] - '0';

If you need to parse anything more complicated than a simple three-character string, you will need a lot more work.

At the end, of course, your program is equivalent to:

int main() {
  int n = '1' - '0';
  int e = '5' - '0';
  cout << n + e << …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Trying to use two packages with badly chosen generic names could be a challenge.

I don't think this is really a problem. First of all, most libraries will try to pick a reasonably unique name for the library, and will usually use the same name for the top-level namespace. Second, typically, users of libraries are reasonably aware of the number of external libraries used and which. So, the odds of one project needing two libraries with the same name, same top-level namespace and conflicting elements within that namespace is pretty low. Third, any decent programmer knows how to wrap a (problematic) external library in a thin wrapper with a good compilation firewall (Cheshire Cat). Finally, if all fails, it is always possible to wrap #includes with an additional namespace, it is tricky and not recommended, but a possible last resort. It is also possible to wrap #includes in an unnamed namespace as well.

Using UUIDs for namespace names is a pretty ridiculous solution, no offense.

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

>>Why is it a bad idea to use the std namespace for my new functions?

You should not put anything in the std namespace. There are only very rare (and advanced) reasons to put anything in the std namespace.

And there is nothing special about the std namespace in this regard, the same goes for any library you use. Any good library will have all its things in at least one top-level namespace (like std, boost, cv, etc.), yours should too. Generally, a library is meant to be _used_, meaning that elements of its namespace are invoked (classes and functions). Libraries are rarely meant to be extended by expecting or allowing a user of the library to add things to the library's namespace. The C++ standard library is one such library which is not meant to be "extended" by the user.

You have to understand that entering the namespace of a library is like entering inside the guts of the library, you get exposed to all the complex inner-workings which are fine-tuned to work without your "extensions". And "using namespace .." is like spilling the guts of the library all over the place.

>>If all of my functions have names which are different than the names of std functions, it is no harm, right?

So.. you know all the names of all the functions and classes (including those which are implementation details, like helper functions), and that is, for all implementations of the standard library, …

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

To create a namespace, you do as follows:
In your header file:

#ifndef MY_HEADER_HPP
#define MY_HEADER_HPP

#include ...

namespace my_name_space {

class my_class {
  //..
};

};

#endif

When you define functions in your cpp file, you also use the same namespace enclosure.

You have to understand the meaning of the statement "using namespace std;". What this statement means is that you "import" all the names that are in the std namespace into the scope where that statement appears. If you do this at the global scope, then you are basically putting all the implementation of the standard libraries into the global namespace. For small programs this is ok, but for library-code or any non-trivial piece of code, you are better leave standard functions in the std namespace, don't import them.

Now, even worse is importing the std namespace (or any other namespace) in a header file. Header files are meant to be included by other headers and source files. If you do a "using namespace .." statement in your header, you are silently importing a namespace into a scope where the "user" does not expect it (by "user" I mean the coder that includes your header file)­. The reason namespaces exist is to create a private naming-space where you can pick smaller, simpler, clearer names for things you program without fear that some other developer of some other library chose the same name for something else. Importing a namespace completely breaks this feature.

It …

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

nmaillet is correct.

But in response to:
>>Also if you see anything in my code that needs to be fixed feel free to tell me about them.

I don't see anything that _needs_ to be fixed, but certain things could be made better.

First, think hard before you use the var-args feature. This is a C feature that is not type-safe. Nothing prevents someone from constructing a Vector and give it a bunch of crazy parameters that will corrupt everything. Type-safety is a blessing for robustness, by-passing type-safety is not something to be done lightly. I think I understand what you are trying to do with this constructor: be able to construct a vector by giving it a list of values. Personally, I would go with the good old fashion way:

Vector(T q1) {
     BOOST_STATIC_ASSERT(D == 1);
     //..
   };
   Vector(T q1, T q2) {
     BOOST_STATIC_ASSERT(D == 2);
     //..
   };
   Vector(T q1, T q2, T q3) {
     BOOST_STATIC_ASSERT(D == 3);
     //..
   };
   //.. etc. for as many as you like.

Of course, if you can use C++0x (upcoming standard), then you can simply use the initializer_list. As so:

Vector(std::initializer_list<T> q);

Second, if you know the length of the vector from a template argument (D), then why don't you make your vector class store a static array? Why pay the price of dynamic memory allocation when it is not necessary? I highly recommend you do that, to actually make that class useful in any way.

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

In this line:

PriceInfo lowest = *(sortedLows.begin());

How can you tell that sortedLows is not empty? If the set/list/map is empty, then the begin() iterator will not be dereferenciable (because it is equal to end() iterator, which is one past the last element). Verify that the container is not empty before dereferencing the begin() iterator.

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

You are using a large amount of stack-based memory (static arrays) and I wouldn't be surprised if the leastSquares method did as well, given the sizes you provide (7120). The "abnormal termination" failure is usually due to stack-overflow, meaning that your program runs out of stack-memory to store the local variables of the functions, in which case, all the OS can do is terminate abruptly. Either find a way to avoid using so much memory (by breaking up the problem, or by using dynamically allocated memory instead), or increase the stack-size for the program (check your compiler's documentation to know how to specify a stack-size that is greater than the default size).