C++ std :: equal - 不测试具有相同大小的2个范围的基本原理?

siv*_*udh 7 c++ stl

我刚刚编写了一些代码来测试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()[)并且相应地采取行动.

  • 它与迭代器而不是容器一起工作在我看来是STL最大的优势之一. (3认同)
  • @ShaChris32:是的,您可以使用 `==` 比较两个列表(或者通常是两个相同类型的标准容器)。 (2认同)
  • @James:我们的想法是将算法从容器中分离出来,而迭代器就是这么做的.也就是说,Alexandrescu最近有一个名为"Iterators Must Go"的演讲,它推荐使用范围代替迭代器.我同意他的看法. (2认同)