views:

39

answers:

1

I'm trying to write a fake vector for my class assignment, and I currently get an error in the member function pushBack. The compiler doesn't seem to like incrementing the SIZE variable which holds the number of elements in the "vector". Is there something I might need to fix? Your assistance would be highly appreciated for helping me with this, and any other problems you might happen to find.

/*
Write a simple program that simulates the behavior of vectors
-You should be able to add and remove elements to the vector
-You should be able to access an element directly.
-The vector should be able to hold any data type.
*/


#include <stdio.h>

template <class T, int SIZE>
class Vector
{
 #pragma region constructors&destructors
 private:
 T vec[SIZE];

 public:

 Vector()
 {}
 ~Vector()
 {}
 #pragma endregion

 template <class T/*, int SIZE*/>
 void defineVec(T var)
 {
  for(int i=0; i<SIZE; i++)
  {
   vec[i] = var;
  }
  //printf("All elements of the vector have been defined with %", var)
  //What should I do when trying to print a data type or variable 
                //of an unspecified one along with the '%'?
 }

 template <class T/*, int SIZE*/>
 void pushBack(T var)
 {
  SIZE ++; //C1205
  vec[SIZE - 1] = var;
 }

 template <class T/*, int SIZE*/>
 void popBack()
 {
  vec[SIZE - 1] = NULL;
  SIZE--;
 }

 //template <class T/*, int SIZE*/>
 void showElements()
 {
  for(int i=0; i<SIZE; i++)
  {
   printf("%d",vec[i]);
   printf("\n");
  }
 }
};

int main()
{
 Vector <int, 5> myints;
 myints.pushBack(6);
 myints.showElements();
 return 0;
}
+3  A: 

You're passing SIZE as a template parameter. Inside the definition of a template, a non-type template parameter is basically a constant -- i.e., you can't modify it.

You'll need to define a separate variable to keep track of how much of the storage in your vector-alike is currently being used.

Jerry Coffin
It also needs some kind of dynamic allocation. If this compiled, it would causes a buffer overflow.
Matthew Flaschen
@Matthew: Well, sort of. It's not written to make use of the space properly, but it *does* allocate space, so dynamic allocation wouldn't be absolutely necessary.
Jerry Coffin
@Jerry, I never said it didn't allocate space. Dynamic allocation is absolutely necessary if he wants to have a `pushBack` method that can be executed an arbitrary number of times; this seems to be a requirement of the assignment. As is, it would easily buffer overflow.
Matthew Flaschen