搜索算法的改进

Improvements to search algorithm

我正在实施一个监控系统,该系统检查计算机上的进程是否 运行,如果不是,则处理它们的 restart/recovery。为此,我有以下功能:

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

这个功能可以用,但我想知道是否有更优雅的方法来做到这一点?

=== 编辑 ===

具体来说,我不是在寻找代码审查,这是我想出的一种假设情况(也不是 university/work 作业),目的是扩展我对 std 算法的了解。我要问的是...

给定两个 std 字符串容器(A 和 B),标准库中是否有一种算法可以创建第三个容器 (C) 来保存 A 中不存在的元素的副本在 B.

我的假设是您有一个程序列表 运行,另一个程序列表应该是 运行。您想要获得应该 运行 但当前不是的所有程序的列表。

这样做的明显方法(特别是考虑到您无论如何都要对列表进行排序)是使用 std::set_difference.

running_processes = get_process_list();

std::sort(begin, end);
std::sort(running_processes.begin(), running_processes.end());

std::vector<std::string> to_restart;

std::set_difference(begin, end, 
                    running_processes.begin(), running_processes.end(),
                    std::back_inserter(to_restart));

for (auto const &name : to_restart)
    func(name);