I wouldn't implement the vector as an array. At least not as you suggested. That way, it will have very poor performance, being just an array. If it actually is implemented that way, it would also need an internal table to keep track of the memory locations and gain performance that way.
So then, i believe that the most effective way to implement it would be as a linked list (double-linked list to allow for backward-iteration). It would have an overhead, of course, but the performance comes with a price, and in this case it's well worth it.
For example if you have a double linked list of integers, you'll need a structure with the actual element of type int and 2 pointers to integer (which in this case will have the same size as int, 4 bytes), leading to use of 12 bytes per element instead of 4. But then suppose you have a large number of elements (maybe 10000) and you want to erase any of it, you wouldn't need to move a single piece of allocated memory, nor to copy. You can just reconnect the nodes of the list and delete the allocated memory for that element. That way you gain a lot in performance/speed. And not to mention that if in the vector you have elements with larger size (perhaps some struct/class, not a primitive type), then the size of the head/tail in the list won't be much of an overhead compared to the overall size. It always will be an overhead, but that's the trade off.
If you don't want any memory overhead, the only solution would be as you suggested with the array, and then do memory reallocation (which in a larger application won't be feasible).
Another thing that i saw in your code was:
-
memcpy( vec[0], vec[1], 3 );
-
cout << vec[0]; // should display 2
-
One thing is that as JosAH suggested, memmove() might be a better solution. I don't think that memset() wouldn't work, since there is not a memory overlap. After all, vec[0] and vec[1] are different objects of same size, no matter if they are next to each other or not.
But why use 3 as a third parameter??? The size of int is 4, not 3. So, in your example it will work, but that's just a coincinence, because you're copying the 1st 3 bytes, leaving the MSB unchanged. If you wanna check it out, try with this:
-
vec[0] = 0x11223344;
-
vec[1] = 0x55667788;
-
memcpy( vec[0], vec[1], 3 );
-
If you think that that code will make the value of vec[0] to be 0x55667788, well... think again. It will be: 0x11667788.
However, when using those functions, it would be safer to put sizeof(int) or sizeof(vec[0]) as a third parameter.
Cheers