加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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个容器是否具有相同的尺寸()?有合理的理由吗?

解决方法

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

怎么样?您没有将容器传递给函数,而是传入迭代器.该函数无法知道第二个容器的大小.它所能做的只是假设用户传递了两个有效的容器范围(即第二个范围被正确指定为半开区间[lst2.begin(),lst2.begin() – lst1.begin()) lst1.end()[)并据此采取行动.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读