sivabudh sivabudh - 27 days ago 6
C++ Question

C++ std::equal -- rationale behind not testing for the 2 ranges having equal size?

I just wrote some code to test the behavior of std::equal, and came away surprised:

int main()
{
try
{
std::list<int> lst1;
std::list<int> lst2;

if(!std::equal(lst1.begin(), lst1.end(), lst2.begin()))
throw std::logic_error("Error: 2 empty lists should always be equal");

lst2.push_back(5);

if(std::equal(lst1.begin(), lst1.end(), lst2.begin()))
throw std::logic_error("Error: comparing 2 lists where one is not empty should not be equal");
}
catch(std::exception& e)
{
std::cerr << e.what();
}
}


The output (a surprise to me):

Error: comparing 2 lists where one is not empty should not be equal


Observation: why is it the std::equal does not first check if the 2 containers have the same
size()
? Was there a legitimate reason?

Answer

Observation: why is it the std::equal does not first check if the 2 containers have the same size() ? Was there a legitimate reason?

How? You do do not pass containers to the function, you pass in iterators. The function has no way of knowing the size of the second container. All it can do is assume bona fide that the user passed in two valid container ranges (i.e. that the second range is correctly specified as the half-open interval [lst2.begin(), lst2.begin() - lst1.begin() + lst1.end()[) and act accordingly.

Comments