Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate the nonexistent find_first_not_of function?

The std::basic_string class template has member functions find_first_of and find_first_not_of.

The <algorithm> header, however, contains only a generic find_first_of.

Question1: Is the absence of

std::find_first_not_of(Iter1 first1, Iter1 last1, Iter2 first2, Iter2 last2)

just an oversight (as for example copy_if) or is it intentionally omitted because the behavior can be achieved with another standard function?

Of course I could write my own find_first_not_of, but

Question2: Is there a ready workaround somewhere in <algorithm>? For example, the absence of copy_if is compensated by the presence of remove_copy_if

Thanks in advance

like image 618
Armen Tsirunyan Avatar asked Jul 27 '11 13:07

Armen Tsirunyan


1 Answers

I had this same problem, the short answer to your question: it's not possible with the standard stl libraries (although it is possible with boost::phoenix).

However, you can write your own closure surrounding the sequence iterators that accepts a parameterized 'Value' variable and returns a bool result.

 template<class Iterator> struct is_not_in_range
{
    Iterator const begin;
    Iterator const end;
is_not_in_range(Iterator const& b, Iterator const& e)
    :   begin(b)
    ,   end(e) {}
    template<class Value> bool operator()(Value & v)
    {
          return std::find(begin,end,v) == end;
    }
};

Then you can do this

std::find_if(begin1, end1,  is_not_in_range<Iterator2>(begin2,end2));

Alternatively, you can write a version that uses less branching, but requires a break->continue (approximated with a goto statement)

template<class Iterator1, class Iterator2> Iterator1 find_first_not_of
(   Iterator1 const& begin1
,   Iterator1 const& end1
,   Iterator2 const& begin2
,   Iterator2 const& end2 )
{
    for(Iterator1 mid1 = begin1; mid1 != end1; ++mid1)
    {
        for(Iterator2 mid2 = begin2; mid2 != end2; ++mid2)
            if(*mid1 == *mid2)
                goto FOUND;
        return mid1;
FOUND:      ;
    }
    return end1;
};
like image 55
Anthony S Avatar answered Nov 15 '22 13:11

Anthony S