std::copy与std::back_inserter引发的惨案

发布时间 2023-09-05 10:56:26作者: ChebyshevTST
#include <iostream>
#include <vector>
#include <numeric>
#include <sstream>


int main() {
    std::vector v{1, 2, 3, 4, 5};
    std::copy(begin(v), end(v), std::back_inserter(v));

    for (const auto& item : v)
        std::cout << item << ' ';
}

原本目的是将vector中的元素再复制一遍,追加到其末尾,然而却发现新增的元素并不是预期中的(并且每次运行都不一样)。大概看了一下copy的实现才发现问题(copy实际源码挺复杂的,进行了不少优化,仅提供简化版本):

template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last,
              OutputIt d_first)
{
    for (; first != last; (void)++first, (void)++d_first)
        *d_first = *first;
 
    return d_first;
}

仔细可以注意到,last是会发生变化的,所以造成了结果不符合预期。

 

可以改用insert实现:

std::vector v{1, 2, 3, 4, 5};
std::vector<int> copied{begin(v), end(v)};
v.insert(end(v), begin(copied), end(copied));