如何使用C ++ 03有效地将一系列项目插入到中间的std :: deque中?

时间:2015-01-09 19:04:26

标签: c++ std time-complexity deque c++03

我正在使用C ++ 03将一个整数序列插入std::deque<int>。我看到在deque中插入一次的唯一方法是使用位置,计数和值的重载或使用位置,开始输入迭代器和结束输入迭代器。如果我可以使用后者,我会这样做:

#include <deque>
#include <boost/iterator/counting_iterator.hpp>

void
insertRecent(const int begin,
             const int end, // Assumes end >= begin
             std::deque<int> &_recent,
             std::deque<int>::iterator insertionPoint)
{
  _recent.insert(insertionPoint,
                 boost::counting_iterator<int>(begin),
                 boost::counting_iterator<int>(end));
}

但是,boost::counting_iterator在我使用的所有平台上都不可用,并且在某些平台上,编译器会遇到错误。因此,我试图通过第一次重载执行此操作,但是想知道是否有更有效的方法来执行此操作:

#include <deque>

void
insertRecent(const int begin,
             const int end, // Assumes end >= begin
             std::deque<int> &_recent,
             std::deque<int>::iterator insertionPoint)
{
  if (begin != end) {
    int offset = begin;
    const size_type count = static_cast<size_type>(end - begin);
    const size_type insertEndDistance = _recent.end() - insertionPoint;

    // Make space for all the items being inserted.
    _recent.insert(insertionPoint, count, begin);

    // Start off at the iterator position of the first item just inserted.
    // In C++11 we can just use the return value from deque::insert().
    std::deque<int>::iterator itr = _recent.end() - (count + insertEndDistance);

    for (; ++offset != end; ) {
      *++itr = offset;
    }
  }
}

我认为这种方法在(end - begin)范围内是线性的,与(_recent.end() - insertionPoint)的距离是线性的。我认为这和我在这里做的一样好吗?

1 个答案:

答案 0 :(得分:1)

你可以制作自己的计数迭代器:

class my_int_iterator {
    int v_;
public:
    my_int_iterator (int v = 0) : v_(v) {}
    int operator * () const { return v_; }
    my_int_iterator & operator ++ () { ++v_; return *this; }
    bool operator != (my_int_iterator mii) const { return v_ != mii.v_; }

    typedef std::input_iterator_tag iterator_category;
    typedef int value_type;
    typedef void difference_type;
    typedef void pointer;
    typedef void reference;
};

void
insertRecent(const int begin,
             const int end, // Assumes end >= begin
             std::deque<int> &_recent,
             std::deque<int>::iterator insertionPoint)
{
  _recent.insert(insertionPoint,
                 my_int_iterator(begin),
                 my_int_iterator(end));
}