Подтвердить что ты не робот

Имитация `continue;`, `break;` в лямбда-foreach-петлях

Я поклонник "петли 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(...).

К сожалению, использование таких lambdas явно предотвращает использование иногда полезных операторов continue; и break;.

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

Есть ли способ имитировать операторы continue; и break; без потери производительности и не сделать синтаксис менее удобным?

4b9b3361

Ответ 1

Замените функцию-член forData на функции-члены begin и end, которые создают итераторы, а затем замените

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

с

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

Однако, если вы по какой-то нераскрытой причине предпочитаете функцию члена forData, тогда вы можете реализовать псевдо-continue и break через некоторое злоупотребление исключениями. Например, цикл Python for основан на исключении. Код драйвера forData затем просто игнорирует исключение continue и исключает исключение break, останавливая итерацию.

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;
        }
    }
}

Альтернативой является требование, чтобы лямбда возвращала значение, которое говорит "break" или "continue".

Наиболее естественным было бы использовать для этого тип перечисления.

Основная проблема с подходом возвращаемого значения, как я вижу, заключается в том, что он захватывает значение результата лямбда, например. он не может тогда (очень легко) использоваться для получения результатов, которые накапливаются в цикле, или что-то в этом роде.


Я бы этого не сделал. Я предпочел бы использовать цикл 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;
    }
}

Ответ 2

Объявите свой forData запрос на лямбду, которая возвращает логическое значение. Когда лямбда возвращает true, выйдите из цикла for.

Затем просто используйте return true; в вашей лямбда для break; и return false; для continue;

И если вам не нужна возможность разрыва, как в вашем последнем примере, достаточно просто заменить continue на return...