简体   繁体   English

使用std :: copy将元素插入向量

[英]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(size_t index, 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

(this means insert worked fine) (这意味着insert效果很好)

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: 但是我绝对不明白为什么这段代码会这样工作,因为在cplusplus.comlink )上,我发现std::copy工作方式如下:

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 executes *result = *first; 执行*result = *first;时,它将7替换为6 *result = *first; and after ++result; ++first; ++result; ++first; ++result; ++first; it will replace 8 with 6 and so on. 它将替换86等。

In myvector iterators are defined like this: myvector迭代器的定义如下:

typedef T* iterator;

and my begin / end is: 我的begin / end是:

iterator begin() {
    return storage_ + 0;
}

iterator end() {
    return storage_ + size_;
}

What you're doing there does not conform to the requirements of std::copy , which include that result NOT be within the range [begin,end) . 您在此处执行的操作不符合std::copy的要求,该要求包括result不在[begin,end)范围内。 So anything's possible; 所以一切皆有可能; you've broken the rules. 你违反了规则。

Anything is possible, that is... including it working correctly. 一切皆有可能,即...包括其正常工作。 It sounds like your particular standard library implementation has decided to be merciful, by noticing that you're violating the requirement and instead delegating to std::copy_backward . 听起来您的特定标准库实现决定仁慈,因为您注意到您违反了该要求,而是委托给了std::copy_backward It's allowed to do this because one possible type of undefined behavior is "stuff still works". 允许这样做是因为一种未定义行为的可能类型是“东西仍然有效”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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