对顺序对使用C ++ 11的for-range语法的方法? [英] Way to Use C++ 11's for-range Syntax for Sequential Pairs?

查看:47
本文介绍了对顺序对使用C ++ 11的for-range语法的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使用for-range循环语法来处理数组中的两个顺序元素?

Is there a way to use for-range loop syntax to process two sequential elements in an array?

示例...

func( std::vector< vec2 > &points )
{
std::vector< float > distances;
for( int i = 0; i < (int)points.size() - 1; i++ )
   {
   auto from = points.at( i );
   auto to   = points.at( i + 1 );

   distances.push_back( magnitude( to - from ) );
   }
}

推荐答案

有没有一种方法可以使用for-range循环语法来处理数组中的两个顺序元素?

Is there a way to use for-range loop syntax to process two sequential elements in an array?

不是开箱即用的.

但是,您可以滚动自己的包装器类和迭代器类以获取所需的内容.

However, you can roll your own wrapper class and an iterator class to get what you need.

包装类的 begin() end()成员函数必须返回一个迭代器,该迭代器的计算结果为 std :: pair 当使用 * 运算符取消引用时.

The begin() and end() member functions of the wrapper class must return an iterator which evaluates to a std::pair when it is dereferenced with the * operator.

这是一个演示程序:

#include <iostream>
#include <vector>

struct VectorWrapper;

struct MyIterator
{
   MyIterator(VectorWrapper const& wrapper, size_t index) : wrapper_(wrapper), index_(index) {}

   std::pair<float, float> operator*();

   MyIterator& operator++()
   {
      ++index_;
      return *this;
   }

   bool operator==(MyIterator const& rhs) const
   {
      return (this->index_ == rhs.index_);
   }

   bool operator!=(MyIterator const& rhs) const
   {
      return (this->index_ != rhs.index_);
   }

   VectorWrapper const& wrapper_;
   size_t index_;
};

struct VectorWrapper
{
   explicit VectorWrapper(std::vector<float>& distances) : distances_(distances) {}

   MyIterator begin() const
   {
      return MyIterator(*this, 0);
   }

   MyIterator end() const
   {
      return MyIterator(*this, distances_.size()-1);
   }

   std::vector<float>& distances_;
};

std::pair<float, float> MyIterator::operator*()
{
   return std::make_pair(wrapper_.distances_[index_], wrapper_.distances_[index_+1]); 
}

int main()
{
   std::vector<float> dist = {1, 2, 3, 4, 5, 6};
   VectorWrapper wrapper(dist);
   for ( auto item : wrapper )
   {
      std::cout << item.first << ", " << item.second << std::endl;
   }
}

及其输出:

1, 2
2, 3
3, 4
4, 5
5, 6

这篇关于对顺序对使用C ++ 11的for-range语法的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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