我刚刚写了一些代码来测试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(),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不首先检查2个容器是否具有相同的尺寸()?有合理的理由吗?