C++ 有条件地向前或向后迭代的优雅方式

C++ 有条件地向前或向后迭代的优雅方式,c++,loops,boost,iterator,reverse,C++,Loops,Boost,Iterator,Reverse,我必须根据布尔标志向前或反向处理std::vector。实现这一点最优雅的方式是什么?在需要反向操作之前,我有: BOOST_FOREACH(const CType &foo, vec) { ... } 然而,现在我有了可怕的表情: for (int i=undoing ? (vec.size()-1) : 0; undoing ? (i >= 0) : (i < vec.size()); undoing ? (i--) : (i++)) { const C

我必须根据布尔标志向前或反向处理
std::vector
。实现这一点最优雅的方式是什么?在需要反向操作之前,我有:

BOOST_FOREACH(const CType &foo, vec) {
    ...
}
然而,现在我有了可怕的表情:

for (int i=undoing ? (vec.size()-1) : 0; undoing ? (i >= 0) : (i < vec.size()); undoing ? (i--) : (i++)) {
    const CType &foo = vec[i];
    ...
}
for(inti=undoing?(向量大小()-1):0;undoing?(i>=0):(i

有更好的方法吗?

添加一个可与正向迭代器或反向迭代器一起使用的模板函数。根据
undoing
的值,使用适当的迭代器调用函数

template <typename Iterator>
void doStuff(Iterator iter, Iterator end)
{
   for ( ; iter != end; ++iter )
   {
      // Do stuff
   }
}

if ( undoing )
{
   doStuff(vec.rbegin(), vec.rend());
}
else
{
   doStuff(vec.begin(), vec.end());
}
模板
void doStuff(迭代器iter,迭代器end)
{
对于(;iter!=结束;++iter)
{
//做事
}
}
如果(撤消)
{
doStuff(vec.rbegin(),vec.rend());
}
其他的
{
doStuff(vec.begin(),vec.end());
}

如何保持循环在0到vector.size之间运行,但按照需要的方向读取数组

int idx;
for (int i =0; i < vec.size(); i ++)
{
   if (undoing) // assuming going forward
     idx = i;
   else // going backwards
     idx = vec.size() - i - 1;

  const CType &foo = vec[idx];
}
intidx;
对于(int i=0;i
我不知道人们会说它优雅,但有:

auto do_it = [](const CType& elem)
             {
                 ...
             };
if (iterate_forward) {
    std::for_each(vec.begin(), vec.end(), do_it);
}
else {
    std::for_each(vec.rbegin(), vec.rend(), do_it);
}

您也可以使用基于Boost.Range的解决方案。它类似于已经提出的使用STL算法的方法

#include <boost/range/adaptor/reversed.hpp>
#include <boost/range/algorithm/for_each.hpp>

// In C++11 lambda expression can be used instead
struct my_fun
{
    void operator()(const CType& elem) const
    {
        /*...*/
    }
};

/*...*/

using namespace boost::adaptors;

if ( iterate_forward )
    boost::for_each(my_vect, my_fun());
else
    boost::for_each(my_vect | reversed, my_fun());
#包括
#包括
//在C++11中,可以使用lambda表达式
构造我的乐趣
{
void运算符()(常量CType&elem)常量
{
/*...*/
}
};
/*...*/
使用名称空间boost::适配器;
if(向前迭代)
boost::为每个人(我的向量,我的乐趣());
其他的
boost::for each(我的向量反向,我的乐趣());

C++11支持吗?我想不会。@Yakk:no,尽管我对这个答案很感兴趣。对(unsigned I=undoding?(vec.size()-1):0;I