简体   繁体   中英

How to implement insert vector c++?

I have to implement a vector class with operator[] , rule of 5, push_back , and insert .

template<class T>
class MyVector
{
private:
    int size_;
    int capacity_;
    T* data;
public:
    typedef T* it;

    it begin();
    it end();
    void push_back(const T& value);

I started to create constructor, copy constructor, move constructor, copy assignment operator, move assignment operator.

I implemented the begin() and end() like this:

template<class T>
typename MyVector<T>::it MyVector<T>::begin()
{
    return data;
}

template<class T>
typename MyVector<T>::it MyVector<T>::end()
{
    return data + size();
}

I don't know how to implement push_back() and insert() .

For push_back() , I thought about something like this:

void push_back(const T & v)
{
    if (size_ < capacity_)
        data [size_++] = v;
}

But for insert() , I have no idea.

Could you help me please to implement insert() ?

Your push_back() is not implemented correctly. It needs to grow the array when the size_ is equal to the capacity_ , to make room for the new value being pushed.

Likewise, your insert() also needs to grow the array, if needed. It can then figure out the index where the new value should go, shift all of the elements after that index up one slot in the array, and then assign the new value to the element at that index.

Try something like this:

template<class T>
void MyVector<T>::grow()
{
    static const int delta = ...; // <-- use whatever value makes sense for your use case...
    int new_cap = capacity_ + delta;
    T* new_data = new T[new_cap];
    for(int i = 0; i < size_; ++i) {
        new_data[i] = std::move(data[i]);
    }
    delete[] data;
    data = new_data;
    capacity_ = new_cap;
}

template<class T>
void MyVector<T>::push_back(const T & v)
{
    if (size_ == capacity_)
        grow();

    data[size_] = v;
    ++size_;
}

template<class T>
void MyVector<T>::insert(typename MyVector<T>::it pos, const T & v)
{
    int index = pos - data;
    if (index < 0 || index > size_)
        return; // or throw...

    if (size_ == capacity_)
        grow();

    for(int i = size_ - 1; i >= index; --i)
        data[i+1] = data[i];

    data[index] = v;
    ++size_;
}

Live Demo

For insert you must.

  • make room for the extra data. (as you also need to do in push_back/emplace_back).
  • move the current data from the insertion point to the new offset.
  • copy the inserted data in.

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