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?
=== EDIT ===
To be specific, I'm not looking for a code review and this is a hypothetical situation (not a university/work assignment either) I came up with in order to expand my knowledge of std algorithms. What I'm asking is...
Given two std containers of strings (A and B), is there an algorithm in the standard library which can create a third container (C) that holds copies of elements from A which are not present in B.
My assumption is that you have one list of programs that are running, and another list of programs that should be running. You want to get a list of any programs that should be running but aren't currently.
The obvious way to do that (especially given that you're sorting the lists anyway) would be to use
std::set_difference
.