更快的环路范围 (C++11)
Faster range for loop (C++11)
我有一些代码来迭代(多变量)数值范围:
#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/相应地更改begin
和end
定义
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
属性。
- C ++枚举范围无法使用-std=c ++ 98进行编译,但使用-std=c ++ 11可以
- C++11 基于范围的 for 循环,用于 std::list
- C++11:没有复制构造函数的自定义基于范围的循环
- 如何在C++11中区分填充构造函数和范围构造函数
- 自动和范围内 for 循环 C++11 不起作用
- 带钥匙的C 11地图定义了一个值范围
- 为什么即使在启用 C++11 并且我包含字符串之后,'stod'仍然没有在此范围内声明?
- C++11 迭代器和返回的 std::unique_ptr 的范围
- C++11:用容器参数定义函数(类似于基于范围的)
- GCC 4.4 不实现 C++11 范围循环.它还支持哪些其他范围循环语法
- 嵌套c++11范围循环,用于查找组合
- 使用基于C++11范围的循环验证数组值?[无矢量]
- 基于C++11范围的自动循环(按值、引用和指针)
- 使用对指针的引用作为循环C++11范围内的序列
- 从矢量中删除项目,而在 C++11 范围内'for'循环?
- 在基于 C++11 范围的'for'循环中获取对 STL 容器元素的引用
- C++11范围内的随机数和显式相似性
- 多维数组上循环的C++11范围
- 关于循环和迭代器的c++11范围
- C++11 范围超过 "tuple"