# When to use vector containers?

• 11-09-2008
thetinman
When to use vector containers?
Should they be used all the time? If so what is the point of have the "new" and "delete" operators? I'm guessing that vectors can sometimes slow things down a bit.

On a side note, I've got a rather complex algorithm, with lots of news and deletes, and things just don't quite look right to me. Here is a section of the code:

Code:

```#include <cmath> #include "poly.hpp" poly::poly () {   corners = new point[3];   pvrt = new vertice[3]; } poly::~poly () {   delete[] corners;   delete[] pvrt; } poly &poly::operator =(const poly &rhs){             if(this != &rhs){       int i;       A = rhs.A;       B = rhs.B;       C = rhs.C;       D = rhs.D;       n = rhs.n;       beta = rhs.beta;       norm = rhs.norm;       delete[] corners;       corners = new point[n];       delete[] pvrt;       pvrt = new vertice[n];       for(i=0;i<n;i++){       corners[i] = rhs.corners[i];       pvrt[i] = rhs.pvrt[i];            } }       return *this;  }```
I could certainly justify using new and delete though, if it is faster that way. This program does tree-like recursion which can take a lot of time.
• 11-09-2008
CornedBee
Quote:

Should they be used all the time?
Don't use them when you know the array size at compile time, and it's not too large for the stack.
Otherwise, yes.

Quote:

If so what is the point of have the "new" and "delete" operators?
They're required to implement vector ;)
Seriously, though, new and delete are the low level stuff. Vector is the high level. You should always use the high level unless you have a very good reason not to.

Quote:

I'm guessing that vectors can sometimes slow things down a bit.
Not really. Sometimes it does, but that's rare. And even then, you first have to prove that the speedup (which will be marginal) is worth the added hassle of manual management.

Quote:

On a side note, I've got a rather complex algorithm, with lots of news and deletes, and things just don't quite look right to me. Here is a section of the code
Are those real compile time constant 3s? If so, the correct thing to do is to make arrays of size 3 direct members of the class, instead of allocating on the heap.
• 11-09-2008
thetinman
Three is the lowest possible size. Four, five, and six are more probable. Fifty would probably be unreasonable.
• 11-09-2008
CornedBee
Well, unless you can give a definite upper bound below 10, making them static arrays would be wrong.

So, vectors. Hey, they even do the assignment thing for you. You can get rid of your custom operator.
• 11-09-2008
Daved
>> Hey, they even do the assignment thing for you. You can get rid of your custom operator.

And feel better knowing that the fact that you're missing a copy constructor (assuming it's not hiding somewhere else) won't cause bad things to happen to your program.