更快的环路范围 (C++11)

Faster range for loop (C++11)

本文关键字:C++11 范围 环路      更新时间:2023-10-16

我有一些代码来迭代(多变量)数值范围:

#include <array>
#include <limits>
#include <iostream>
#include <iterator>
template <int N>
class NumericRange : public std::iterator<double, std::input_iterator_tag>
{
public:
  NumericRange() {
    _lower.fill(std::numeric_limits<double>::quiet_NaN());
    _upper.fill(std::numeric_limits<double>::quiet_NaN());
    _delta.fill(std::numeric_limits<double>::quiet_NaN());
  }
  NumericRange(const std::array<double, N> & lower, const std::array<double, N> & upper, const std::array<double, N> & delta):
    _lower(lower), _upper(upper), _delta(delta) {
    _state.fill(std::numeric_limits<double>::quiet_NaN());
  }
  const std::array<double, N> & get_state() const {
    return _state;
  }
  NumericRange<N> begin() const {
    NumericRange<N> result = *this;
    result.start();
    return result;
  }
  NumericRange<N> end() const {
    NumericRange<N> result = *this;
    result._state = _upper;
    return result;
  }
  bool operator !=(const NumericRange<N> & rhs) const {
    return in_range();
    //    return ! (*this == rhs);
  }
  bool operator ==(const NumericRange<N> & rhs) const {
    return _state == rhs._state && _lower == rhs._lower && _upper == rhs._upper && _delta == rhs._delta;
  }
  const NumericRange<N> & operator ++() {
    advance();
    if ( ! in_range() )
      _state = _upper;
    return *this;
  }
  const std::array<double, N> & operator *() const {
    return _state;
  }
  void start() {
    _state = _lower;
  }
  bool in_range(int index_to_advance = N-1) const {
    return ( _state[ index_to_advance ] - _upper[ index_to_advance ] ) < _delta[ index_to_advance ];
  }
  void advance(int index_to_advance = 0) {
    _state[ index_to_advance ] += _delta[ index_to_advance ];
    if ( ! in_range(index_to_advance) ) {
      if (index_to_advance < N-1) {
    // restart index_to_advance
    _state[index_to_advance] = _lower[index_to_advance];
    // carry
    ++index_to_advance;
    advance(index_to_advance);
      }
    }
  }
private:
  std::array<double, N> _lower, _upper, _delta, _state;
};
int main() {
   std::array<double, 7> lower{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};
   std::array<double, 7> upper{{1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}};
   std::array<double, 7> delta{{0.03, 0.06, 0.03, 0.06, 0.03, 0.06, 0.03}};
  NumericRange<7> nr(lower, upper, delta);
  int c = 0;    
  for (nr.start(); nr.in_range(); nr.advance()) {
    ++c;
  }
  std::cout << "took " << c << " steps" << std::endl;    
  return 0;
}

在我的计算机上,使用 g++ -std=c++11 -O3(或使用 gcc <4.7 -std=c++0x)编译大约需要 13.8 秒。

如果我将main函数更改为使用基于范围的 for 循环:

  for (const std::array<double, 7> & arr : nr) {
    ++c;
  }

运行时间增加到 29.8 秒。巧合的是,当使用std::vector<double>而不是std::array<double, N>时,这个~30秒的运行时间几乎与原始运行时相同,导致我相信编译器无法展开基于范围的for循环生成的代码。

有没有办法拥有原始的速度并仍然使用基于范围的 for 循环?


我尝试过:

我可以通过更改NumericRange中的两个成员函数来获得基于范围的 for 循环所需的速度:

bool operator !=(const NumericRange<N> & rhs) const {
  return in_range();
  //    return ! (*this == rhs);
}
const NumericRange<N> & operator ++() {
  advance();
  //    if ( ! in_range() )
  //      _state = _upper;
  return *this;
}

但是,此代码感觉设计不佳,因为!= operator无法按预期工作 通常对于数字运算,我使用 < 来终止循环而不是==。我想找到第一个超出范围的值,但由于数值误差,分析这样做可能不会给出准确的答案。

您如何强制!= operator的行为与<类似,而不会误导将看到我的代码的其他人?我只是将begin()end()函数设为私有,但它们需要为基于范围的 for 循环公开。

非常感谢您的帮助。

我而言,问题在于您没有正确使用范围结构。


让我们退后一步:

void foo(std::vector<int> const& v) {
    for (int i: v) {
    }
}

请注意 range-for 如何遍历向量以提取整数


出于某些原因,您选择不实现迭代器来从begin桥接到end,而是重用您正在迭代的副本,即使它只是非常轻微的变化,并且您正在做大量额外的工作(在副本和检查中)......

注意:std::iterator<double, ...>表示operator*应返回double&

如果你想使用新的成语,你必须符合它的期望。

期望是使用迭代器进行迭代,而不是通过一遍又一遍地复制原始对象(略有修改)。这是C++成语。

这意味着您需要将对象切成两半:在迭代对象中拉出所有不可变的内容,以及在迭代器中修改的内容。

据我所知:

  • _lower_upper_delta是固定
  • 迭代变量_state

因此,您将拥有:

template <typename> class NumericRangeIterator
template <unsigned N> // makes no sense having a negative here
class NumericRange {
public:
    template <typename> friend class NumericRangeIterator;
    typedef NumericRangeIterator<NumericRange> iterator;
    typedef NumericRangeIterator<NumericRange const> const_iterator;
    static unsigned const Size = N;
    // ... constructors
    iterator begin(); // to be defined after NumericRangeIterator
    iterator end();
    const_iterator begin() const;
    const_iterator end() const;
private:
    std::array<double, N> _lower, _upper, _delta;
}; // class NumericRange
template <typename T>
class NumericRangeIterator: public
    std::iterator< std::array<double, T::Size>,
                   std::forward_iterator_tag >
{
public:
    template <unsigned> friend class NumericRange;
    NumericRangeIterator(): _range(0), _state() {}
    NumericRangeIterator& operator++() {
        this->advance();
        return *this;
    }
    NumericRangeIterator operator++(int) {
        NumericRangeIterator tmp(*this);
        ++*this;
        return tmp;
    }
    std::array<double, T::Size> const& operator*() const {
        return _state;
    }
    std::array<double, T::Size> const* operator->() const {
        return _state;
    }
    bool operator==(NumericRangeIterator const& other) const {
        return _state != other._state;
    }
    bool operator!=(NumericRangeIterator const& other) const {
        return !(*this == other);
    }

private:
    NumericRangeIterator(T& t, std::array<double, T::Size> s):
        _range(&t), _state(s) {}
    void advance(unsigned index = T::Size - 1);  // as you did
    void in_range(unsigned index = T::Size - 1); // as you did
    T* _range;
    std::array<double, T::Size> _state;
}; // class NumericRangeIterator

template <unsigned N>
auto NumericRange<N>::begin() -> typename NumericRange<N>::iterator {
    return iterator(*this, _lower);
}
template <unsigned N>
auto NumericRange<N>::end() -> typename NumericRange<N>::iterator {
    return iterator(*this, _upper);
}

通过所有这些设置,您可以编写:

for (auto const& state: nr) {
}

auto将被推导出为std::array<double, nr::Size>.

注意:不确定iterator是否有用,也许只是const_iterator,因为它在某种程度上是一个错误的迭代;你不能通过迭代器进入范围对象来修改它。

编辑:operator==太慢了,如何让它变得更好?

我建议作弊。

1/修改迭代器的构造函数

NumericRangeIterator(): _range(0), _state() {}               // sentinel value
NumericRangeIterator(T& t): _range(&t), _state(t._lower) {}

2/调整迭代以在末尾创建新的"哨兵"值

void advance() {
    // ...
    if (not this->in_range()) {        // getting out of the iteration ?
       *this = NumericRangeIterator(); // then use the sentinel value
    }
}

3/相应地更改beginend定义

template <unsigned N>
auto NumericRange<N>::begin() -> typename NumericRange<N>::iterator {
    return iterator(*this);
}
template <unsigned N>
auto NumericRange<N>::end() -> typename NumericRange<N>::iterator {
    return iterator();
}

4/使用哨兵使==更加平等

bool operator==(NumericRangeIterator const& other) const {
    return _range == other._range and _state == other._state;
}

现在,在整个迭代过程中,==都短路了,因为其中一个_range为空,另一个不是。只有在最后一次调用时,才会真正比较两个_state属性。