Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to call std::equal on potentially shorter input if I know there will be difference detected within size of input

Tags:

c++

stl

While doing some nw programming I stumbled upon the following dilemma:

Im doing something like:

static const string my_ip_prefix = "111.222.233";

//going through list of IPs where one might have prefix my_ip_prefix

if (equal(my_ip_prefix .begin(), my_ip_prefix .end(), ip_list[i].begin())))
{
//
}

If I know IPs from ip_list can be shorter than my_ip_prefix, but that in that case they differ from my_ip_prefix on at least one position in them is it safe to call equal? Example : is it safe to call it with ip "10.20.30.4"

Aka does standard mandates sequential checks starting from front and break; in std::equal?

It might seem obvious that A is yes, but maybe ISO ppl wanted to give option implementations to parallelize...

like image 656
NoSenseEtAl Avatar asked Dec 19 '22 18:12

NoSenseEtAl


1 Answers

If we look at the cppreference entry for std::equal it says:

[...]where last2 denotes first2 + (last1 - first1)

which means that ip_list[i] will need to be at least as long. This corresponds with the draft C++11 standard which in section 25.2.11 Equal says:

template<class InputIterator1, class InputIterator2>
  bool equal(InputIterator1 first1, InputIterator1 last1,
             InputIterator2 first2);

Returns: true if for every iterator i in the range [first1,last1) the following corresponding conditions hold: *i == *(first2 + (i - first1)), [...]

In C++14 you have a version of that takes a end iterator for the second input, same section as C++11:

template<class InputIterator1, class InputIterator2>
  bool equal(InputIterator1 first1, InputIterator1 last1,
             InputIterator2 first2, InputIterator2 last2);

and it says:

If last1 - first1 != last2 - first2, return false. [...]

like image 199
Shafik Yaghmour Avatar answered Feb 16 '23 04:02

Shafik Yaghmour