我刚刚编写了一些代码来测试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();
}
}
Run Code Online (Sandbox Code Playgroud)
输出(给我一个惊喜):
Error: comparing 2 lists where one is not empty should not be equal
Run Code Online (Sandbox Code Playgroud)
观察:为什么std :: equal首先检查2个容器是否相同size()?有合理的理由吗?
Kon*_*lph 12
观察:为什么std :: equal首先检查2个容器是否具有相同的大小()?有合理的理由吗?
怎么样?你没有传递容器到函数,你传入迭代器.该函数无法知道第二个容器的大小.它所能做的只是假设用户传递了两个有效的容器范围(即第二个范围被正确地指定为半开区间[ lst2.begin(),lst2.begin()- lst1.begin()+ lst1.end()[)并且相应地采取行动.
| 归档时间: |
|
| 查看次数: |
3102 次 |
| 最近记录: |