std :: insert_iterator和iterator无效 [英] std::insert_iterator and iterator invalidation

查看:234
本文介绍了std :: insert_iterator和iterator无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写一个泛型, intersperse 函数。该函数应该将一个给定的元素穿插到一个元素序列中。

I tried writing a generic, in place, intersperse function. The function should intersperse a given element into a sequence of elements.

#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 or am I missing something about insert_iterator that makes this kind of usage possible?

推荐答案


此示例仅适用于插入时不会使其迭代器无效的容器。 p>

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

这将是一种可能性。另一种方法是不将算法放在原位(即输出到不同的容器/输出迭代器)。

That would be one possibility. Another would be not making the algorithm in-place (ie. output to a different container/output-iterator).


关于insert_iterator,使这种使用可能吗?

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

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

No. insert_iterator is meant for repeated inserts to a single place of a container eg. by a transform algorithm.

这篇关于std :: insert_iterator和iterator无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆