gpt4 book ai didi

c++ - std::insert_iterator 和迭代器失效

转载 作者:行者123 更新时间:2023-11-30 04:29:44 24 4
gpt4 key购买 nike

我尝试编写一个通用的、就地的、intersperse 函数。该函数应将给定元素散布到一系列元素中。

#include <vector>
#include <list>
#include <algorithm>
#include <iostream>

template<typename ForwardIterator, typename InserterFunc>
void intersperse(ForwardIterator begin, ForwardIterator end, InserterFunc ins,
// we cannot use rvalue references here,
// maybe taking by value and letting users feed in std::ref would be smarter
const ForwardIterator::value_type& elem) {
if(begin == end) return;
while(++begin != end) {
// bugfix would be something like:
// begin = (ins(begin) = elem); // insert_iterator is convertible to a normal iterator
// or
// begin = (ins(begin) = elem).iterator(); // get the iterator to the last inserted element

// begin now points to the inserted element and we need to
// increment the iterator once again, which is safe
// ++begin;
ins(begin) = elem;
}
}

int main()
{
typedef std::list<int> container;
// as expected tumbles, falls over and goes up in flames with:
// typedef std::vector<int> container;
typedef container::iterator iterator;
container v{1,2,3,4};

intersperse(v.begin(), v.end(),
[&v](iterator it) { return std::inserter(v, it); },
23);
for(auto x : v)
std::cout << x << std::endl;
return 0;
}

该示例仅适用于不会使其无效的容器插入时的迭代器。我应该简单地摆脱迭代器和接受一个容器作为参数,还是我遗漏了一些关于insert_iterator 使这种用法成为可能?

最佳答案

The example works only for containers that do not invalidate their iterators on insertion.

没错。

Should I simply get rid of the iterators and accept a container as the argument

那是一种可能性。另一种方法是不就地制作算法(即输出到不同的容器/输出迭代器)。

am I missing something about insert_iterator that makes this kind of usage possible?

没有。 insert_iterator 用于重复插入到容器的单个位置,例如。通过变换算法。

关于c++ - std::insert_iterator 和迭代器失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9154408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com