我刚刚写了一些代码来测试std::equal的行为,并感到惊讶:
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();
}
}
输出结果(对我来说很惊讶):
Error: comparing 2 lists where one is not empty should not be equal
观察:为什么 std::equal 函数不先检查两个容器是否具有相同的
size()
?这样做是否有合理的原因?
size()
。在容器要求中,C++标准仅表示size()
应具有常数时间复杂度。 - James McNellissize()
。 - Mike Seymour