
-----------------------------------
wtd
Sat Dec 18, 2004 3:02 pm

[C++] Don't use arrays in C++!
-----------------------------------
But... don't you tell us to use arrays?

Yes, in Turing, and other languages, where arrays are either well-implemented, or there's simply no decent alternative.

C++ has a better alternative

The vector class in the Standard Template Library provides a more flexible, powerful alternative to using arrays.

Whoa, whoa, whoa... what's the Standard Template Library?

The STL is a collection of classes and functions which revolve around the C++ concept of templates, whereby we can create types and functions which operate on many types of data, without immediately specifying those types, or writing separate classes or functions for every type.

Don't worry, GCC includes an implementation of the STL, as do most other compilers these days.  Visual C++ 6.0, it should be noted, has an implementation of it, but that implementation is quite bad.  If you use this compiler, you may be led to believe the STL is a bad thing, when it's really the compiler at fault.

A simple template class

Now, we could write the following trivial code:

#include 
#include 

class int_math
{
   private:
      int original;
   public:
      int_math(int original_) : original(original_) { }
      int add(int other) const { return original + other; }
      int value() const { return original; }
};

class double_math
{
   private:
      double original;
   public:
      double_math(double original_) : original(original_) { }
      double add(double other) const { return original + other; }
      double value() const { return original; }
};

int main()
{
   int_math a(8);
   double_math b(7.0);

   std::cout > grades[num_grades];
      num_grades++;

      do
      {
         std::cout > answer;
      } while (!(answer == 'y' || answer == 'n'));
   }

   int sum = 0;

   for (int i = 0; int i < num_grades; i++)
   {
      sum += grades[i];
   }

   std::cout > temp_grade;
      grades.push_back(temp_grade);

      do
      {
         std::cout > answer;
      } while (!(answer == 'y' || answer == 'n'));
   }

   std::cout >(std::istream& in, grades_collection& g)
{
   int temp_grade;
   in >> temp_grade;
   g.push_back(temp_grade);
   return in;
}

int main()
{
   grades_collection grades;
   char answer = 'y';

   while (answer == 'y')
   {
      std::cin >> grades;

      do
      {
         std::cout > answer;
      } while (!(answer == 'y' || answer == 'n'));
   }

   std::cout 