vendredi 1 septembre 2017

Improvements to search algorithm

I'm implementing a monitor system which checks if processes are running on the computer and then handles their restart/recovery if they are not. To do this I have the following function:

std::size_t ProcessPolicy::is_running_with_restart(
    std::vector<std::string>::iterator begin,
    std::vector<std::string>::iterator end,
    std::function<void( std::string const & )> func )
{
    auto running_processes = std::vector<std::string>{};

    {
        //--------------
        //Platform specific code to populate the vector
        //with the names of all running processes
        //--------------
    }


    //sort both the lists
    if ( std::is_sorted( begin, end ) == false )
    {
        std::sort( begin, end );
    }

    auto running_begin = std::begin( running_processes );
    auto running_end = std::end( running_processes );

    std::sort( running_begin, running_end );


    //compare sorted lists processing differences
    auto count = std::size_t{ 0 };

    std::for_each(
        begin,
        end,
        [func, &running_begin, &running_end]( std::string const &curr ) {

            running_begin = std::find_if(
                running_begin,
                running_end,
                [&curr]( std::string const &s ) {
                    return ( s.compare( curr ) >= 0 );
                } );

            if ( running_begin != running_end )
            {
                if ( *running_begin != curr )
                {
                    func( curr );
                    ++count;
                }

                ++running_begin;
            }
            else
            {
                func( curr );
                ++count;
            }

        } );


        return count;
    }

This function is working but I'm wondering whether there is a more elegant way to do this?

Aucun commentaire:

Enregistrer un commentaire