Domanda

std::equal() is unsafe because the function cannot know whether it will overrun the length of the second container to be compared. That is:

std::vector< int > v( 100 );
std::vector< int > w( 10 );
bool same = std::equal( v.begin(), v.end(), w.begin() );

...will result in a buffer overrun for w.

Naturally we can test for these things (v.size() == w.size()), but compilers like Visual Studio 2010 still report the function itself as unsafe. And indeed it is unsafe in some fundamental sense: a team of programmers of varying levels of experience will eventually forget to compare sizes.

A safe alternative is easy to implement.

template< typename Iter1, typename Iter2 >
bool equal_safe( Iter1 begin1, Iter1 end1, Iter2 begin2, Iter2 end2 )
{
    while( begin1 != end1 && begin2 != end2 )
    {
        if( *begin1 != *begin2 )
        {
            return false;
        }
        ++begin1;
        ++begin2;
    }
    return begin1 == end1 && begin2 == end2;
}

But is there a safe alternative in the standard library?

È stato utile?

Soluzione

In C++14, the standard library will contain a version of std::equal that takes two pairs of iterators, similar to your safe_equal. Same for std::mismatch and std::is_permutation.

Altri suggerimenti

You can also use std::lexicographical_compare twice to determine if either sequence is less than the other.

vector has an operator== that first checks the size. In your example, just use the condition v==w.

I have wanted such a feature myself. I have not been able to find any facilities in the standard library.

If you are willing to use boost. Boost.Range has equal which I think is what your are looking for http://www.boost.org/doc/libs/1_53_0/libs/range/doc/html/range/reference/algorithms/non_mutating/equal.html

I got same problem and solved it by checking size of vector before equal.

  std::vector< int > v( 100 );
  std::vector< int > w( 10 );
  bool same = (v.size() == w.size()) && std::equal( v.begin(), v.end(), w.begin() );
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top