hi, suppose i have a vector class like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
template <class T>
class vec {
private:
int length;
T *v;
public:
vec();
vec(int n);
....
....
~vec();
};
// zero argument constructor
template <class T>
vec<T>::vec() : length(0), v(0) {}
// 1-arg constructor
template <class T>
vec<T>::vec(int n) : length(n), v(new T[n]) {}
template <class T>
vec<T>::~vec() {
if (v != 0) {
delete[] (v);
}
}
| |
Here, under the 1-arg constructor I create a vector with length n using
new
. Now suppose I would like to resize this vector, say by removing the last 2 elements, say, then
1) Is it better to implement a resize/remove function as a member function here, for example, as,
|
vec<T> & remove(const int n, string index); // ex: n = 2, index = "last"
| |
or implement as a separate function template. I understand it can be done both ways, but I would like to know which one is better and why?
2) While implementing this function, say as a member function, how do I go about deleting just the last 2 elements of this vector? Is it possible without using a temporary array (for backup) and just do
delete v[n-1]; delete v[n-2];
and reset the length property?
thank you!