C std :: equal – 不测试具有相同大小的2个范围的理由吗?
发布时间:2020-12-16 04:57:23 所属栏目:百科 来源:网络整理
导读:我刚刚写了一些代码来测试std :: equal的行为,并且惊讶地走了出来: int main(){ try { std::listint lst1; std::listint lst2; if(!std::equal(lst1.begin(),lst1.end(),lst2.begin())) throw std::logic_error("Error: 2 empty lists should always be equ
我刚刚写了一些代码来测试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个容器是否具有相同的尺寸()?有合理的理由吗? 解决方法
怎么样?您没有将容器传递给函数,而是传入迭代器.该函数无法知道第二个容器的大小.它所能做的只是假设用户传递了两个有效的容器范围(即第二个范围被正确指定为半开区间[lst2.begin(),lst2.begin() – lst1.begin()) lst1.end()[)并据此采取行动. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |