在基于 lambda 的 foreach 循环中模拟 'continue;', 'break;“

Simulating `continue;`, `break;` in lambda-based foreach loops

本文关键字:continue break 模拟 lambda 循环 foreach      更新时间:2023-10-16

我是"基于lambda的foreach循环"的粉丝:

class SomeDataStructure
{
    private:
        std::vector<SomeData> data;
    public:
        template<typename TF> void forData(TF mFn)
        {
            for(int i{0}; i < data.size(); ++i)
                mFn(i, data[i]);
        }
};
SomeDataStructure sds;
int main()
{
   sds.forData([](auto idx, auto& data)
   {
       // ...
   });
}

我认为对于更复杂的数据结构来说,这是一个很好的抽象,因为它允许用户使用其他参数直观地循环其内容。编译器优化应保证与传统for(...)循环相同的性能。

不幸的是,像这样使用 lambda 显然会阻止使用有时有用的 continue;break; 语句。

sds.forData([](auto idx, auto& data)
{
    // Not valid!
    if(data.isInvalid()) continue;
});

有没有办法模拟continue;break;语句而不会造成任何性能损失并且不会使语法变得不那么方便?

将成员函数forData替换为生成迭代器的成员函数 beginend,然后替换

sds.forData([](auto idx, auto& data)
{
    // Not valid!
    if(data.isInvalid()) continue;
});

for( auto& data : sds )
{
    if(data.isInvalid()) continue;
}

但是,如果您出于某种未公开的原因宁愿拥有 forData 成员功能,那么您可以通过滥用异常来实现伪continuebreak。例如,Python 的 for 循环基于异常。然后,forData驱动程序代码将忽略继续异常,并通过停止迭代来遵守中断异常。

template<typename TF> void forData(TF mFn)
{
    for(int i{0}; i < data.size(); ++i)
    {
        try
        {
            mFn(i, data[i]);
        }
        catch( const Continue& )
        {}
        catch( const Break& )
        {
            return;
        }
    }
}

另一种方法是要求 lambda 返回一个值,该值显示"break"或"continue"。

最自然的做法是为此使用枚举类型。

在我看来,返回值方法的主要问题是它劫持了 lambda 结果值,例如,它不能(非常容易(用于生成循环累积的结果,或者类似的东西。


不过,我不会这样做。我宁愿使用基于范围的for循环,如本答案开头所建议的那样。但是,如果您这样做,并且您担心效率,那么请记住,首先要做的是测量。


附录:添加一个类似 Python 的枚举函数。

您可以实现一个类似 Python 的枚举函数,该函数生成集合的逻辑视图,以便集合看起来像(值、索引(对的集合,非常适合在基于范围的for循环中使用:

cout << "Vector:" << endl;
vector<int> v = {100, 101, 102};
for( const auto e : enumerated( v ) )
{
    cout << "  " << e.item << " at " << e.index << endl;
}

以下代码(最低限度,只是为了这个答案而拼凑在一起(显示了执行此操作的一种方法:

#include <functional>       // std::reference_wrapper
#include <iterator>         // std::begin, std::end
#include <utility>          // std::declval
#include <stddef.h>         // ptrdiff_t
#include <type_traits>      // std::remove_reference
namespace cppx {
    using Size = ptrdiff_t;
    using Index = Size;
    template< class Type > using Reference = std::reference_wrapper<Type>;
    using std::begin;
    using std::declval;
    using std::end;
    using std::ref;
    using std::remove_reference;
    template< class Derived >
    struct Rel_ops_from_compare
    {
        friend
        auto operator!=( const Derived& a, const Derived& b )
            -> bool
        { return compare( a, b ) != 0; }
        friend
        auto operator<( const Derived& a, const Derived& b )
            -> bool
        { return compare( a, b ) < 0; }
        friend
        auto operator<=( const Derived& a, const Derived& b )
            -> bool
        { return compare( a, b ) <= 0; }
        friend
        auto operator==( const Derived& a, const Derived& b )
            -> bool
        { return compare( a, b ) == 0; }
        friend
        auto operator>=( const Derived& a, const Derived& b )
            -> bool
        { return compare( a, b ) >= 0; }
        friend
        auto operator>( const Derived& a, const Derived& b )
            -> bool
        { return compare( a, b ) > 0; }
    };
    template< class Type >
    struct Index_and_item
    {
        Index               index;
        Reference<Type>     item;
    };
    template< class Iterator >
    class Enumerator
        : public Rel_ops_from_compare< Enumerator< Iterator > >
    {
    private:
        Iterator        it_;
        Index           index_;
    public:
        using Referent = typename remove_reference<
            decltype( *declval<Iterator>() )
            >::type;
        friend
        auto compare( const Enumerator& a, const Enumerator& b )
            -> Index
        { return a.index_ - b.index_; }
        auto operator->() const
            -> Index_and_item< Referent >
        { return Index_and_item< Referent >{ index_, ref( *it_ )}; }
        auto operator*() const
            -> Index_and_item< Referent >
        { return Index_and_item< Referent >{ index_, ref( *it_ )}; }
        Enumerator( const Iterator& it, const Index index )
            : it_( it ), index_( index )
        {}
        auto operator++()
            -> Enumerator&
        { ++it_; ++index_; return *this; }
        auto operator++( int )
            -> Enumerator
        {
            const Enumerator result = *this;
            ++*this;
            return result;
        }
        auto operator--()
            -> Enumerator&
        { --it_; --index_; return *this; }
        auto operator--( int )
            -> Enumerator
        {
            const Enumerator result = *this;
            --*this;
            return result;
        }
    };
    template< class Collection >
    struct Itertype_for_ { using T = typename Collection::iterator; };
    template< class Collection >
    struct Itertype_for_<const Collection> { using T = typename Collection::const_iterator; };
    template< class Type, Size n >
    struct Itertype_for_< Type[n] > { using T = Type*; };
    template< class Type, Size n >
    struct Itertype_for_< const Type[n] > { using T = const Type*; };
    template< class Collection >
    using Itertype_for = typename Itertype_for_< typename remove_reference< Collection >::type >::T;

    template< class Collection >
    class Enumerated
    {
    private:
        Collection&     c_;
    public:
        using Iter = Itertype_for< Collection >;
        using Eter = Enumerator<Iter>;
        auto begin()    -> Eter { return Eter( std::begin( c_ ), 0 ); }
        auto end()      -> Eter { return Eter( std::end( c_ ), std::end( c_ ) - std::begin( c_ ) ); }
        //auto cbegin() const -> decltype( c_.cbegin() )  { return c_.cbegin(); }
        //auto cend() const   -> decltype( c_.cend() )    { return c_.cend(); }
        Enumerated( Collection& c )
            : c_( c )
        {}
    };
    template< class Collection >
    auto enumerated( Collection& c )
        -> Enumerated< Collection >
    { return Enumerated<Collection>( c ); }
}  // namespace cppx
#include <iostream>
#include <vector>
using namespace std;
auto main() -> int
{
    using cppx::enumerated;
    cout << "Vector:" << endl;
    vector<int> v = {100, 101, 102};
    for( const auto e : enumerated( v ) )
    {
        cout << "  " << e.item << " at " << e.index << endl;
    }
    cout << "Array:" << endl;
    int a[] = {100, 101, 102};
    for( const auto e : enumerated( a ) )
    {
        cout << "  " << e.item << " at " << e.index << endl;
    }
}

声明您的forData需要一个返回布尔值的 lambda。 当 lambda 返回 true 时,脱离你的 for 循环。

然后只需在 lambda 中使用 return true; 进行break;return false;用于continue;

如果您不需要中断功能,就像上一个示例一样,只需将continue替换为return就足够了......