jeudi 28 mai 2015

using std::copy to insert element into vector

In my hand-write vector I needed to implement insert function, so I did it like this:

void insert(const T& x) { 
    std::copy(begin() + index, end() - 1, begin() + index + 1);
    new(storage_ + index) T(x); // "storage_" is my vector's inner array
}

And this works absolutely correct on test like this:

myvector<int> v;
for (int i = 0; i < 10; i++)
    v.push_back(i + 1);
v.insert(5, 0); // insert(size_t position, const T& element)

This outputs:

1 2 3 4 5 0 6 7 8 9 10

But I absolutely don't understand why this code works the way it is because on cplusplus.com (link) I found that std::copy works like this:

template<class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
    while (first!=last) {
        *result = *first;
        ++result; ++first;
    }
return result;
}

But doesn't it mean, that if I call

std::copy(begin() + index, end() - 1, begin() + index + 1);

It will replace 7 with 6 when it will execute *result = *first; and after ++result; ++first; it will replace 8 with 6 and so on.

In myvector iterators are defined like this:

typedef T* iterator;

and my begin/end is:

iterator begin() {
    return storage_ + 0;
}

iterator end() {
    return storage_ + size_;
}

Aucun commentaire:

Enregistrer un commentaire