• for_each与伪函数


    1.for_each就是封装好的循环遍历函数。共三个参数,前两个为迭代器,最后一个参数为函数指针或者伪函数。

    函数原型如下(effective stl):

    template< typename InputIterator, typename Function >
    Function for_each( InputIterator beg, InputIterator end, Function f ) {
        while ( beg != end )
            f( *beg++ );
    }


    2.伪函数就是重载了()运算符的struct或class.

    struct DelPointer
    {
        template<typename T>void operator()(T* ptr) 
        {
            delete ptr;
        }
    }
    

    3.for_each实例。

    #include <vector>
    #include <iostream>
    
    struct State
    {
        State( int state ) : m_state( state ){}
        ~State() { std::cout << "~State(), m_state=" << m_state << std::endl; }
    
        void setState( int state ){ m_state = state; }
        int getState() const{ return m_state; }
    
        void print() const { std::cout << "State::print: " << m_state << std::endl; }
    
    private:
        int m_state;
    };
    
    int main()
    {
        std::vector<State*> vect;
        ......................................
        ......................................
        std::for_each( vect.begin(), vect.end(), DeletePointer() );
        vect.clear();
    
        system( "pause" );
        return 0;
    }

    4.如果觉得每次都要定义一个伪函数比较麻烦,STL也给我们提供了模板函数,用于简化这种情况。

    #include <vector>
    #include <iostream>
    
    struct State
    {
        State( int state ) : m_state( state ){}
        ~State() { std::cout << "~State(), m_state=" << m_state << std::endl; }
    
        void setState( int state ){ m_state = state; }
        int getState() const{ return m_state; }
    
        void print() const { std::cout << "State::print: " << m_state << std::endl; }
    
    private:
        int m_state;
    };
    
    int main()
    {
        std::vector<State*> vect;
    
        vect.push_back( new State(0) );
        vect.push_back( new State(1) );
        vect.push_back( new State(2) );
        vect.push_back( new State(3) );
    
        std::for_each( vect.begin(), vect.end(), std::mem_fun( &State::print ) );
        
        system( "pause" );
        return 0;
    }
  • 相关阅读:
    LightOJ 1422 Halloween Costumes(区间dp)
    zoj 3537 Cake(区间dp)
    POJ 2955 Brackets(区间dp)
    HDU 1058 Humble Numbers(dp)
    uva 10934 Dropping water balloons(转载)
    树形dp
    Manacher算法求回文半径
    poj-1236.network of schools(强连通分量 + 图的入度出度)
    hdu-2255.奔小康赚大钱(最大权二分匹配)
    poj-2289.jamies contact groups(二分答案 + 二分多重匹配)
  • 原文地址:https://www.cnblogs.com/wsswlyy/p/6323468.html
Copyright © 2020-2023  润新知