Advice on a better way to extend C++ STL container with user-defined methods

后端 未结 8 1567
星月不相逢
星月不相逢 2020-12-01 08:41

I inherited from C++ STL container and add my own methods to it. The rationale was such that to the clients, it will look act a regular list, yet has application-specific me

8条回答
  •  暖寄归人
    2020-12-01 09:01

    why you need extend vector in this way?

    use standard with your functors.
    e.g.

    std::min_element, std::max_element

    int max_a = std::max_element
            ( 
                v.begin(), 
                v.end(), 
                boost::bind( 
                    std::less< int >(),
                    bind( &Item::a, _1 ), 
                    bind( &Item::a, _2 ) 
                )
            )->a;
    

    std::accumulate - for calculate avarage

    const double avg_c = std::accumulate( v.begin(), v.end(), double( 0 ), boost::bind( Item::c, _1 ) ) / v.size(); // ofcourse check size before divide  
    

    your ItemList::SpecialB() could be rewrited as:

    int accumulate_func( int start_from, int result, const Item& item )
    {
       if ( item.SpecialB() < start_from )
       {
           result -= item.SpecialB();
       }
       return result;
    }
    
    if ( v.empty() )
    {
        throw sometghing( "empty vector" );
    }
    const int result = std::accumulate( v.begin(), v.end(), v.front(), boost::bind( &accumulate_func, v.front(), _1, _2 ) );
    

    BTW: if you don't need access to members, you don't need inheritance.

提交回复
热议问题