简体   繁体   中英

pop_back and erase for a vector class C++

I'm trying to write the pop_back and erase member functions for my vector class. However I realized I can not use delete. Any suggestions for how I can get rid of an element?

template <class T>
class Vector{
private:
int current_size, capacity;
T* arr;

public:

Vector();
unsigned int size();
void grow();
void push_back(const T& elt);
void pop_back();
T& at(int pos);
T& front();
T& back();
bool empty();
void insert (const T&elt, int pos);
void erase(int pos);
Vector<T>& operator=(const Vector& v);
T& operator[](int n);

};

template <class T>
void Vector<T>::pop_back(){
if(!empty()){
    delete arr[current_size-1];
    current_size--;
    }
 }

template <class T>
void Vector<T>::erase(int pos){
if(!empty() && pos>=0 && pos<current_size) {
    for (int i=pos; i<(current_size-1); i++){
        arr[i]=arr[i+1];
    }
    delete arr[current_size-1];
    current_size--;
 }
}

To call the destructor on something not allocated with regular new you would do something like this:

arr[current_size-1].~T();

Keep in mind that when allocating the objects in the array you probably also want to be making sure you call placement new on them as well, otherwise you're dealing with uninitialized objects. For example:

new (&arr[some_index]) T();

(you will need to include the header file <new> to do this)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM